Division, UVa 72(暴力求解)

题目链接:https://vjudge.net/problem/UVA-725

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

题意概括:输入正整数n,按从小到大的顺序输出所有形如abcde/fghij = n的表达式,其中a~j恰好 为数字0~9的一个排列(可以有前导0),2≤n≤79。

解题思路:枚举0~9的所有排列?没这个必要。只需要枚举fghij就可以算出abcde,然后判断是否 所有数字都不相同即可。不仅程序简单,而且枚举量也从10!=3628800降低至不到1万,而且 当abcde和fghij加起来超过10位时可以终止枚举。

#include<stdio.h>
#include<string.h>
int a[11]; //用来存储1-9出现的次数
bool check(int x,int y)
{
    memset(a,0,sizeof(a));
    if(x>98765) return false;
    for(int j=0;j<5;j++)
    {
        a[x%10]++; a[y%10]++;
        x/=10;  y/=10;
    }
    for(int j=0;j<=9;j++)
    {
        if(a[j]!=1) return false;
    }
    return true;
}
int main(int argc, char const *argv[])
{
    int n,flag,cas=0;
    while(~scanf("%d",&n)&&n)
    {
        flag=1;
    for(int i=1234;i<=98765;i++)
    {
        if(check(n*i,i))
        {
            flag=0;
            printf("%5d / %5d = %d\n",n*i,i,n );
        }
    }
    if(flag) printf("There are no solutions for %d.\n",n);
    printf("\n");
}
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/zjl192628928/p/9292865.html