UVa725 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.

首先自己分析的话有点不知道如何下手,看了书上LRJ老师的提示。于是知道了枚举除数即可。那么从1到99999吗?貌似也刚好能过,但是应该是可以缩小范围的。那么我们先去找除数的最大值,如果除数最大,那么对应的商应该最小,N最小是2,所以除数最大不超过50000。由于加起来的十位必须都含有0-9且各不相同,所以除数的最小值应该是1234。另外,不管0是不是在被除数这边,肯定不能有前导0,因此得到被除数一定大于10000。对于判断符合条件的是否为0-9的全排列,我用了map处理(貌似一个数组就行了 orz)

代码:

#include <iostream>
#include <string>
#include <map>
using namespace std;
bool flag;  //判断是否存在答案
int m;
bool judge(int x,int y){  
    map<int,int> mp;
    if(x<10000) mp[0]++;  //假设被除数为四位数,那么前导0要特判
    while(x){
        mp[x%10]++;
        x/=10;
    }
    while(y){
        mp[y%10]++;
        y/=10;
    }
    for(int i=0;i<9;i++){
        if(mp[i]!=1) return false;
    }
    return true;
}

void solve(int n){
    flag=0;
    for(int i=1234;i<50000;i++){
        if(i*n>10000 && i*n<100000 && judge(i,i*n)){  //被除数范围是[1234,50000)
            flag=1;
            if(i<10000) printf("%d / 0%d = %d\n",i*n,i,n); //对于除数包含前导0
            else printf("%d / %d = %d\n",i*n,i,n);
        }
    }
}
int main()
{
        //freopen("in.txt","r",stdin);
        int kase=0;
        while(scanf("%d",&m) && m){
            if(kase++) printf("\n");  //最后一行不能有回车否则PE
            if(m>79){ printf("There are no solutions for %d.\n",m); continue; }
            solve(m);
            if(!flag) printf("There are no solutions for %d.\n",m);
        }
    return 0;
}

发布了128 篇原创文章 · 获赞 7 · 访问量 5284

猜你喜欢

转载自blog.csdn.net/qq_44691917/article/details/104379641
今日推荐