【题目描述】
给定n个正整数,将它们分组,使得每组中任意两个数互质。至少要分成多少个组?
【输入】
第一行是一个正整数n。1 ≤ n ≤ 10。
第二行是n个不大于10000的正整数。
【输出】
一个正整数,即最少需要的组数。
【输入样例】
6
14 20 33 117 143 175
【输出样例】
3
一组一组添加元素直到把所有元素添加完,再查看一共用来多少组
#include<bits/stdc++.h>
using namespace std; using ll = long long;
int dir[4][2] = { 1, 0, -1, 0, 0, 1, 0, -1 };
//using lll = __int128; template <class T> istream& read(T& x, istream& cin = std::cin) { T num = 0; bool f = 0; char ch = 0; while (!isdigit(ch)) { f |= ch == '-'; if (!cin.get(ch)) return cin; }while (isdigit(ch)) { num = (num << 3) + (num << 1) + (ch ^ 48); if (!cin.get(ch)) break; }x = f ? -num : num; return cin; }template <class T> ostream& write(T x, ostream& cout = std::cout) { if (x < 0) cout.put('-'), x = -x; if (x > 9) write(x / 10); cout.put(x % 10 + '0'); return cout; }ostream& operator<<(ostream& cout, lll x) { write(x); return cout; }istream& operator>>(istream& cin, lll& x) { return read(x); }bool check(int i, int j);
const int N = 1e3 + 10, mod = 1e9 + 7, INF = 0x3f3f3f3f;
int n, m, a[N], st[N];
int group[N][N], ans = N;
void init() {
cin >> n;
for (int i = 0; i < n; i++)
cin >> a[i];
return;
}
inline int gcd(int a, int b) {
int t = 0;
while (b) {
t = b;
b = a % b;
a = t;
}
return a;
}
bool check(int group[], int gc, int i) {
for (int j = 0; j < gc; j++) {
if (gcd(a[group[j]], a[i]) > 1)
return false;
}
return true;
}
void dfs(int u, int gc, int tc, int start) {
if (u >= ans)
return;
if (tc == n) {
ans = u;
}
bool flag = true;
for (int i = start; i < n; i++) {
if (!st[i] && check(group[u], gc, i)) {
st[i] = true;
group[u][gc] = i;
dfs(u, gc + 1, tc + 1, i + 1);
st[i] = false;
flag = false;
}
}
if (flag) dfs(u + 1, 0, tc, 0);
}
void solve() {
dfs(1, 0, 0, 0);
cout << ans;
return;
}
int main(void) {
ios::sync_with_stdio(0); cin.tie(0); cout << setprecision(6) << fixed;
int TT = 1;
//cin >> TT;
for (int ii = 1; ii <= TT; init(), solve(), ii++, cout << "\n") {}
return 0;
}