Files
python/TangDou/LanQiaoBei/LanQiaoBei13ShengSai_ZJ_II/MaiTangYuan_DFS.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

74 lines
1.3 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
const int N = 30;
int a[N];
int n;
//最终答案
int res;
//互质
bool isHz(int a, int b) {
for (int i = 2; i <= min(a, b); i++) //a,b可能存在的公因子
if (a % i == 0 && b % i == 0)
return false;
return true;
}
bool found = false; //最终是不是能表示出来 found=true是可以表达,found=false是不能表达
//能表示
void dfs(int sum, int u) { //用a[]中所有元素组合,能不能表示出x这个数字,如果能返回true,否则返回false
if (u == n + 1) {
if (sum == 0)
found = true;
return;
}
//尝试当前a[u]选择i个
for (int i = 0; sum >= i * a[u]; i++) //i是枚举的a[u]这个数的个数
dfs(sum - i * a[u], u + 1);
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++)
cin >> a[i];
//排一下序,由小到大
sort(a + 1, a + 1 + n);
//a数组中,是不是存在两个互质的数
bool flag = false;
int mx;//疑似上线
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++)
if (isHz(a[i], a[j])) {
flag = true;
mx = a[i] * a[j] - a[i] - a[j];
break;
}
if (flag)
break;
}
if (flag) {
for (int i = 1; i <= mx; i++) {
//一定要记得清空
found = false;
dfs(i, 1);
if (!found)
res++;
}
cout << res << endl;
} else
cout << -1 << endl;
return 0;
}