题目描述
给定n个正整数,将它们分组,使得每组中任意两个数互质。至少要分成多少个组?
【输入】
第一行是一个正整数n。1 ≤ n ≤ 10。
第二行是n个不大于10000的正整数。
【输出】
一个正整数,即最少需要的组数。
样例
in:
6
14 20 33 117 143 175
out:
3
算法
dfs + 顺序搜索
代码
#include <bits/stdc++.h>
using namespace std;
const int N = 15;
int a[N], g[N][N],n;
int ans=0x3f3f3f3f;
bool v[N];
int gcd(int x, int y) {
return y == 0 ? x : (gcd(y,x%y));
}
bool check(int a[],int len, int x) {
for (int i = 0; i < len; ++i) {
if (gcd(a[i], x) != 1) return false;
}
return true;
}
void dfs(int u,int gt,int w,int cnt) {
//u:当前组,gt当前组的长度
//w当前的选择的个数,cnt当前组的选择个数(保证单调)
if (u > ans) return;
if (w == n) {
ans = min(ans, u);
return;
}
bool flag = 1;
for (int i = cnt; i < n; ++i) {
if (!v[i]&&check(g[u],gt,a[i])) {
g[u][gt] = a[i];
v[i] = 1;
flag = 1;
dfs(u,gt+1,w+1,i+1);
v[i] = 0;
}
}
if(flag) dfs(u+1,0,w,0);//贪心
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
for (int i = 0; i < n; ++i) cin >> a[i];
dfs(1, 0, 0, 0);
cout << ans;
return 0;
}