我用DFS解了一下这个题,直接暴力也可以,不过我想练练DFS
然后,,本来应该挺简单的,结果tmp/=10这处位置写错了,一直WA,,然后,,,调了好久,才找出来。
还有就是PE,,格式也有要求........
//思路:每位由0-9进行遍历,判断是否使用过,如未用,选择下一位的数。数位够5以后,计算tmp
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <map>
using namespace std;
int a=0, n, cnt = 0, used[10] = {0};
int flag = 0;
void dfs()
{
int tmp = a*n, cntt = 0;
//5位
if(cnt == 5) {
// cout << a << endl;
for (int i = 0; i < 10; i++) {
// cout << i << " first:" << used[i] <<" ";
// getchar();
if (used[i])
cntt++;
}
// cout << "cntt"<< cntt << endl;
//不符合要求
if (cntt != 5 || tmp > 99999) {
// cout << a << ":a cntt:"<< cntt << endl;
return;
}
cntt = 0;
while (tmp) {
if (used[tmp % 10] == 0) {
cntt++;//个数
used[tmp % 10] = 1;//防止11234
tmp /= 10;//这部分刚开始的tmp /= 10,写在了if外面,导致WA
}
else break;
}
if (cntt == 5) {
flag = 1;
tmp = a * n;
printf("%05d / %05d = %d\n", a * n, a, n);
/* //还原
while (tmp) {
used[tmp % 10] = 0;
tmp /= 10;
}
return;*/
}
//还原
tmp = a * n;
while (cntt--) {
used[tmp % 10] = 0;
tmp /= 10;
}
// break;
/* for (int i = 0; i < 10; i++) {
cout << i << " second:" << used[i] <<" ";}
*/
return;
}
//
/*
map<int, int>test;
test.clear();
if(cnt == 5){
if(tmp >99999 || tmp < 0 || a <0)
return;
int b[10], k = 0;
while(tmp && test[tmp%10]==0) {
b[k++] = tmp%10;
test[tmp%10]++;
tmp/=10;
}
if(k != 5 || used[b[0]] || used[b[1]] ||used[b[2]] ||used[b[3]] ||used[b[4]])
return;
else {
flag = 1;
printf("%05d / %05d = %d\n", a * n, a, n);
}
}
*/
//遍历搜索
for(int j=0; j<10; j++){
if(used[j]){
continue;
}
cnt ++;
// cout << cnt << endl;
a = a*10+j;
// cout << a << ":" << j << " cnt:" << cnt << endl;
used[j] = 1;//已用
// cout << used[j] << "first1:" <<j <<endl;
dfs();
cnt--;
a = floor(a/10);//退一位
used[j] = 0;//还原
//cout<< used[j] << "second2:" <<j << endl;
}
return;
}
int main()
{
int r = 0;
while(cin >> n && n) {
if(r > 0)
printf("\n");//没有这步会PE
dfs();
if (flag == 0) {
printf("There are no solutions for %d.\n", n);
}
r++;
a=0;
cnt = 0;
used[10] = {0};
flag = 0;
}
return 0;
}