[最大公约数] 枚举/暴力

Description

给定 n 个数, 从中选出 K 个。
Alice 想让 K 个数的最大公约数尽可能大, 求最大的最大公约数。 n <= 5e5

Solution

注意到数据范围,可以直接暴力从大到小枚举最大公约数,判断是否有大于K个的他的倍数,如果找到直接输出即可

Code

#include<bits/stdc++.h>
#define mem(a,b) memset(a,b,sizeof(a))
typedef long long ll;
typedef unsigned long long ull;
using namespace std;

int cnt[600000 + 10]; 

int main() {
	//freopen("test.txt", "r", stdin);
	ios::sync_with_stdio(false);
	cin.tie(0);
	int N, K;
	cin >> N >> K;
	int maxx = -1;
	int temp;
	for (int i = 1; i <= N; i++) {
		cin >> temp;
		cnt[temp]++;
		maxx = max(maxx, temp);
	}
	for (int i = maxx; i >= 1; i--) {
		int co = 0;
		for (int j = i; j <= maxx; j += i) {
			co += cnt[j];
			if (co >= K) {
				cout << i << endl;
				return 0;
			}
		}
	}
	return 0;
}

猜你喜欢

转载自www.cnblogs.com/ez4zzw/p/12601813.html
今日推荐