uva725 Division

题目描述:

abcde / fghij =N

a,b···j 为0~9任意一个数,且互相不同

任意给一个n(2<=n<=79),输出满足条件的可能


思路1:10!只有不到400w,直接暴力枚举即可

#include 
#include 
#include 
#include 
using namespace std;

int a[]= {1,0,2,3,4,5,6,7,8,9};
int ansx[4000000];
int ansy[4000000];
int v[4000000];
int main()
{
    int t=0;
    do
    {
        ++t;
        int x=a[0]*10000+a[1]*1000+a[2]*100+a[3]*10+a[4];
        int y=a[5]*10000+a[6]*1000+a[7]*100+a[8]*10+a[9];
        if(x%y==0)
        {
            v[t]=x/y;
            ansx[t]=x;
            ansy[t]=y;
        }
        else
            v[t]=-1;
    }
    while(next_permutation(a,a+10));
    int n;
    int flag=false;
    while(scanf("%d",&n)==1)
    {
        if(n==0)
            break;
        if(flag)///wrong answer
        printf("\n");
        bool f=false;
        for(int i=1; i<=t; i++)
            if(v[i]==n)
            {
                printf("%d / ",ansx[i]);
                if(ansy[i]>9999)
                    printf("%d = ",ansy[i]);
                else
                    printf("0%d = ",ansy[i]);
                printf("%d\n",n);
                f=true;
            }
        if(!f)
            printf("There are no solutions for %d.\n",n);
        flag=true;
    }
    return 0;
}
收获:最后换行符不能多输出,否则wrong answer


思路2:可以只枚举后一位,10!/ 5!,不到10w ,通过判断前面是否符合条件即可

/*
    暴力:对于每一个数都判断,是否数字全都使用过一遍
*/
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

const int MAXN  = 1e4 + 10;
const int INF = 0x3f3f3f3f;
int vis[10];

bool ok(int x, int y)
{
    memset (vis, 0, sizeof (vis));
    for (int i=1; i<=5; ++i)
    {
        vis[x%10]++;    vis[y%10]++;
        if (vis[x%10] > 1 || vis[y%10] > 1)    return false;
        x /= 10;    y /= 10;
    }

    return true;
}

int main(void)        //UVA 725 Division
{
    //freopen ("UVA_725.in", "r", stdin);

    int n, cnt = 0;
    while (scanf ("%d", &n) == 1)
    {
        if (n == 0)    break;
        if (cnt++)    puts ("");

        int one = 0;
        for (int i=1234; i<=100000/n; ++i)
        {
            if (i * n > 98765)    break;
            if (ok (i, i*n) == true)
            {
                printf ("%05d / %05d = %d\n", n*i, i, n);    one++;
            }
        }

        if (!one)    printf ("There are no solutions for %d.\n", n);
    }

    return 0;
}


/*
There are no solutions for 61.
*/




你可能感兴趣的:(枚举)