uva 725 Division
Write a program that finds and displays all pairs of 5-digit numbers that between them use the digits 0 through 9 once each, such that the first number divided by the second is equal to an integer N, where 2<=N <=79. That is,
abcde / fghij =N
where each letter represents a different digit. The first digit of one of the numerals is allowed to be zero.
Input
Each line of the input file consists of a valid integer N. An input of zero is to terminate the program.
Output
Your program have to display ALL qualifying pairs of numerals, sorted by increasing numerator (and, of course, denominator).
Your output should be in the following general form:
xxxxx / xxxxx =N
xxxxx / xxxxx =N
.
.
In case there are no pairs of numerals satisfying the condition, you must write “There are no solutions for N.”. Separate the output for two different values of N by a blank line.
Sample Input
61
62
0
Sample Output
There are no solutions for 61.
79546 / 01283 = 62
94736 / 01528 = 62
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; bool com(char a, char b) { return a>b; } char ans[11]="9876543210"; char s[11]; int main() { int n, pro, m=0; bool flag=false; while(scanf("%d", &n)!=EOF&&n) { if(m>0) printf("\n"); m++;//輸出技巧 flag=false; for(int i=1234; i<=50000; i++) { pro=n*i; if(pro>98765) break; if(i<10000) sprintf(s, "%d%d%d", 0, i, pro); else sprintf(s, "%d%d", i, pro); sort(s, s+10, com); if(strcmp(s, ans)==0) { printf("%d / %05d = %d\n", pro, i, n); flag=true; } } if(!flag) printf("There are no solutions for %d.\n", n); } return 0; }
這題屬於入門級暴力求解法。在進行暴力求解枚舉時,我們應該進行適當的分析。比如這一題,兩個五位數都可以有前導零。我們可以分析一下被除數是不可能前導零的。證明很容易,假設被除數有前導零,說明被除數只是四位數,那么除數必須要五位數,很明顯不合題意,因為N>=2;
在進行枚舉時,我們可以發現被除數枚舉到50000即可(還可以更小,但感覺50000已經優化的可以了)。一旦n*i大於被除數,即可終止for循環。
這是用到的技巧的輸出技巧,sprintf,sort;
不得不說,UVA是很嚴格的,我第一次提交時WA,后來debug是發現我答案多了一行空格。空格處理方法見代碼。
我的主要思路是把含有前導零的除數和不含有前導零的除數分開處理。輸入到字符數組里,然后sort排序。先定義一個0-9的字符數組(已經排好序列),然后用strcmp比較即可,我感覺我的這種方法比網上的其他代碼簡潔而且比較好理解。如有不同見解,請在評論中告知。