又有一段時間沒寫博客了,本應把寫博客當成家常便飯的.(對於算法,個人認為沒必要刷題,應該更關注算法思路,解題技巧和創新思路)
現在進入第七章的學習,暴力求解法
注意: 即使采用暴力法求解問題,對問題進行一定的分析往往會讓算法更簡潔,高效.
如題:
輸入正整數n,按從小到大順序輸出所有形如 abcde / fghij = n 的表達式,其中a - j恰好為數字0-9的一個排列(可以有前導0)2<=n <=79
分析: 枚舉0 -9 所有 排列? 沒必要,我們只需要枚舉fghij 就可以算出abcde,然后判斷所有數字都不相同即可.
上代碼:
// UVa725 Division // Rujia Liu #include<cstdio> #include<cstring> #include<algorithm> using namespace std; int main() { int n, kase = 0; char buf[99]; while(scanf("%d", &n) == 1 && n) { int cnt = 0; if(kase++) printf("\n"); for(int fghij = 1234; ; fghij++) { int abcde = fghij * n;//題目規則 sprintf(buf, "%05d%05d", abcde, fghij);//格式化 if(strlen(buf) > 10) break;//長度超過10不符合 sort(buf, buf+10);//按順序排列10個數字 bool ok = true; for(int i = 0; i < 10; i++)//判斷是否都不相同 if(buf[i] != '0' + i) ok = false; if(ok) { cnt++; printf("%05d / %05d = %d\n", abcde, fghij, n); } } if(!cnt) printf("There are no solutions for %d.\n", n); } return 0; }
分數拆分問題:
輸入正整數k,扎到所有正整數 x >= y ,使得 1/k = 1/x + 1/y
分析: 既然要枚舉,那么我們就要知道枚舉的范文,上式進行變形后得: y = (1 + y/x) k ,易知, y <= 2k ,這樣我們就找到了我們的枚舉范圍了 , k+1 <= y <= 2k
上代碼:
//分數拆分 Fractions Again UVa10976 #include<cstdio> #include<vector> using namespace std; int main(){ int k; while(scanf("%d", &k) == 1 && k){ vector<int> X, Y; for(int y = k+1; y <= k*2; y++){ if(k*y % (y-k) == 0){ X.push_back(k*y/(y-k)); Y.push_back(y); } } printf("%d\n", X.size()); for(int i = 0; i < X.size(); i++) printf("1/%d = 1/%d + 1/%d\n", k, X[i], Y[i]); } return 0; }