题目链接
https://www.luogu.com.cn/problem/P1618
题目意思什么明确,最近刚学会搜索于是第一时间想到了全排列找特定的解,但是写完之后发现怎么也不对,一直输出无解,经过不断地调试和思考,我发现自己画蛇添足地在搜索函数中的条件语句中添加了一个判断,如果符合就return,然而如果return的话后面的回溯就不会执行,所以函数在搜索到一半就停止了,在这里告诫自己回溯之前一定不可以return,上代码
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
int a, b, c;
int arr[10];
int m[10];
int exist;
void search(int t) {
//1~9共9个数枚举全排列组成三个三位数
for (int i = 1; i <= 9; i++) {
if (arr[i] == 0) {
arr[i] = 1;
m[t] = i;
if (t == 9) {
int a1 = m[1] * 100 + m[2] * 10 + m[3];
int b1 = m[4] * 100 + m[5] * 10 + m[6];
int c1 = m[7] * 100 + m[8] * 10 + m[9];
if (a1 * b == b1 * a && b1 * c == c1 * b) {
cout << a1 << " " << b1 << " " << c1 << endl;
exist = 1;
}
}
else
search(t + 1);
arr[i] = 0;//回溯
}
}
}
int main() {
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
cin >> a >> b >> c;
search(1);
if (!exist)
cout << "No!!!" << endl;
return 0;
}
搜索很容易想到但是搜索耗费的时间也是非常多的,特别是像上面的没有剪枝的搜索,好在最后ac了,为了减少时间,我又换了枚举法来写。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
int arr[10];
int main() {
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
int a, b, c;
int t = 1, exist = 0;
cin >> a >> b >> c;
for (int i = 123; i < 333; i++) {
int m1 = i, m2 = i * b / a, m3 = i * c / a;
for (int j = 0; j < 3; j++) {
arr[m1 % 10] = 1;
m1 /= 10;
}
for (int j = 0; j < 3; j++) {
arr[m2 % 10] = 1;
m2 /= 10;
}
for (int j = 0; j < 3; j++) {
arr[m3 % 10] = 1;
m3 /= 10;
}
for (int j = 1; j <= 9; j++) {
if (arr[j] == 0)t = 0;
}
if (t == 1) {
cout << i << " " << i * b / a << " " << i * c / a << endl;
exist = 1;
}
for (int j = 1; j <= 9; j++) {
arr[j] = 0;
}
t = 1;
}
if (!exist)
cout << "No!!!" << endl;
return 0;
}
枚举只循环200多次,自然运行速度要比搜索快的多