首页 > 其他分享 >CF1732A Bestie

CF1732A Bestie

时间:2022-10-24 20:14:43浏览次数:29  
标签:return gcd int dfs CF1732A cost Bestie ans

思路

观察数据\(n \le 20\)
直接暴力。
我们直接算所有数的\(GCD\),然后枚举\(1\)~\(n\)的每一个数要不要选,然后选的话,就把原来的\(GCD\)和当前枚举的数\(GCD\)一下,最后求最小值就好了。

代码

#include <iostream>
using namespace std;
const int N = 30;
int n;
int a[N];
int ans,cost;
int gcd (int a,int b) {
	if (!b) return a;
	return gcd (b,a % b);
}
void dfs (int u,int g,int cost) {
	if (g == 1) {
		ans = min (ans,cost);
		return ;
	}
	if (u > n) return ;
	dfs (u + 1,gcd (g,u),cost + n - u + 1);
	dfs (u + 1,g,cost);
}
int main () {
	int T;
	cin >> T;
	while (T--) {
		cin >> n;
		int g;
		for (int i = 1;i <= n;i++) {
			cin >> a[i];
			if (i == 1) g = a[i];
			else g = gcd (g,a[i]);
		}
		if (n == 1) {
			if (a[1] == 1) puts ("0");
			else puts ("1");
			continue;
		}
		if (g == 1) {
			puts ("0");
			continue;
		}
		ans = 2e9;
		dfs (1,g,0);
		cout << ans << endl;
	}
	return 0;
}

标签:return,gcd,int,dfs,CF1732A,cost,Bestie,ans
From: https://www.cnblogs.com/incra/p/16822620.html

相关文章

  • A. Bestie
    A.BestieYouaregivenanarray$a$consistingof$n$integers$a_1,a_2,\dots,a_n$.Friendsaskedyoutomakethegreatestcommondivisor(GCD)ofallnumbe......