题目:
输入整数n,按从小到大顺序输出所有形如abcde/fghij=n的表达式,其中a~j 恰好为0~9的一个排列(可以有前导0),2<=n<=79
解题思路:
暴力枚举。
下面这代码暴力dfs,结果超时了。
代码如下:
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int N = 13;
bool vis[N];
bool vis2[N];
int n;bool check(int sum_a) {int sum_b = sum_a * n;if (!sum_b)return false;if (sum_b > 99999)return false;if (sum_a+sum_b > 1000000000) return false;memcpy(vis2, vis, sizeof(vis));while (sum_b) {vis2[sum_b % 10] = true;sum_b = sum_b / 10;}for (int i = 0; i <= 9; i++) {if (!vis2[i])return false;}return true;
}
bool flag;bool dfs(int u, int sum_a) {if (u == 6)if (check(sum_a)) {flag = true;printf("%05d / %05d = %d\n", sum_a * n, sum_a, n);}for (int i = 0; i <= 9; i++) {if (!vis[i]) {vis[i] = true;dfs(u + 1, sum_a * 10 + i);vis[i] = false;}}return false;
}int main() {while (cin >> n, n) {memset(vis, 0, sizeof(vis));dfs(1, 0);if (!flag)printf("There are no solutions for %d.\n", n);cout << endl;flag = false;}return 0;
}
让我们看看sprintf的妙用!!!
代码如下:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
char s[20];int main() {int n;while (cin >> n, n) {bool flag1 = true;for (int fghij = 1234;; fghij++) {int abcde = fghij * n;sprintf(s, "%05d%05d", abcde, fghij);if (strlen(s) > 10)break;sort(s, s + 10);bool flag = true;for (int i = 0; i < 10; i++) {if (s[i] != '0' + i)flag = false;}if (flag) {flag1 = false;printf("%05d / %05d = %d\n", abcde, fghij, n);}}if (flag1) {printf("There are no solutions for %d.\n", n);}}return 0;
}
但是代码提交后,会显示
那是因为UVA的输出太…,所以我们学到东西就行了!!!