题目描述:输入正整数n,按从小到大的顺序输出形如abcde / fghij = n的表达式,其中a~j恰好为0-9的一个排列(可以有前导0),2<=n<=79.
找不到这样的解则输出 There are no solutions for n.
解题过程:
一开始想着用全排列 枚举所有的排列情况(此处实现可以用dfs深搜,也可以用STL的next_permutation来枚举所有排列可能),但是这样会TLE。书上讲的是 值只枚举 fghij 然后计算abcde 然后哦判断是否每个数字都用了一次 这样就可以大量的节省时间,可以顺利AC;
#include <iostream>
#include <algorithm>
#include <memory.h>
#define Debug 0
using namespace std;
int main()
{
int n, t = 0;
#if Debug//此处用来调试
freopen("D:\\Documents\\Desktop\\in.txt","r",stdin);
freopen("D:\\Documents\\Desktop\\out.txt","w",stdout);
#endif
while(cin >> n,n)
{
if(t++)//第一次不输出换行,其他情况每次输出前 先换行
cout<<endl;
int flag = 1;//flag 记录该数字是否有解
for(int a = 1234; a<=50000; a++)//遍历fghij的所有可能
{
int tmp_a = a*n, tmp_b = a;//计算abcde
if(tmp_a > 98765)
continue;
bool vis[10];//vis统计数字是否出现 出现为true 没出现为false
memset(vis,0,sizeof(vis));
if(tmp_b < 10000)//小于10000 认为0出现了
vis[0] = 1;
while(tmp_a)
{
vis[tmp_a%10] = 1;
tmp_a /= 10;
}
while(tmp_b)
{
vis[tmp_b%10] = 1;
tmp_b /= 10;
}
int k;
for(k = 0; k<10; k++)
if(!vis[k])
break;
if(k == 10)
{
flag = 0;
if(a < 10000)
cout<<a*n<<" / "<<0<<a<<" = "<<n<<endl;
else
cout<<a*n<<" / "<<a<<" = "<<n<<endl;
}
}
if(flag)
cout<<"There are no solutions for "<<n<<"."<<endl;
}
return 0;
}