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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值