分成互质组(搜索与图论、dfs)

【题目描述】
给定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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值