C. Enlarge GCD(暴力出奇迹)Codeforces Round #511 (Div. 2)

原题链接: https://codeforces.com/problemset/problem/1047/B

在这里插入图片描述
测试样例

Input
3
1 2 4
Output
1
Input
4
6 9 15 30
Output
2
Input
3
1 1 1
Output
-1

Note

In the first example, the greatest common divisor is 1 in the beginning. You can remove 1 so that the greatest common divisor is enlarged to 2. The answer is 1.

In the second example, the greatest common divisor is 3 in the beginning. You can remove 6 and 9 so that the greatest common divisor is enlarged to 15. There is no solution which removes only one integer. So the answer is 2.

In the third example, there is no solution to enlarge the greatest common divisor. So the answer is −1.

题意: 给定一个整数序列,现在你需要删除最少的元素使得这个整数序列的最大公约数比原来的最大公约数,若可以,输出删除的最少元素数,否则输出- 1 1 1

解题思路: 既然我们是想要让这个比原来的最大公约数大,而最大不会大过 1.5 ⋅ 1 0 7 1.5\cdot10^7 1.5107,所以我们是可以枚举这个公约数的,虽然这可能会超时,但我们确实没有别的方法去解决此问题。暴力出奇迹嘛,再做点优化,在我们枚举过程中,如果枚举数不符合,那么我们完全有理由认为它的倍数都不符合(这里还请自行理解。)所以我们可以对不符合的数做标记,这样可以提高极大的枚举效率。OK,具体看代码。

AC代码

/*
*邮箱:unique_powerhouse@qq.com
*blog:https://me.csdn.net/hzf0701
*注:文章若有任何问题请私信我或评论区留言,谢谢支持。
*
*/
#include<bits/stdc++.h>//POJ不支持

#define rep(i,a,n) for(int i=a;i<=n;i++)
#define per(i,a,n) for(int i=a;i>=n;i--)

using namespace std;

const int inf=0x3f3f3f3f;//无穷大。
const int maxn=1e5;//限定值。
typedef long long ll;

int n;
int cnt[maxn];
bool vis[maxn];
int gcd(int n,int m){
	int temp=m;
	while(n%m){
		temp=n%m;
		n=m;
		m=temp;
	}
	return m;
}
int main(){
	while(cin>>n){
		int temp;
		memset(cnt,0,sizeof(cnt));
		memset(vis,0,sizeof(vis));
		int result=0;
		rep(i,1,n){
			cin>>temp;
			if(result==0){
				result=temp;
			}
			else{
				result=gcd(temp,result);
			}
			cnt[temp]++;
		}
		//开始暴力遍历。
		int ans=n;//假设
		for(int i=result+1;i<maxn;i++){
			if(!vis[i]){
				temp=0;//统计公约数的个数。
				//如果没有被测试过。
				for(int j=i;j<maxn;j+=i){
					//i的倍数都无效了。
					vis[j]=true;
					temp+=cnt[j];
				}
				ans=min(ans,n-temp);
			}
		}
		if(ans<n){
			cout<<ans<<endl;
		}
		else{
			cout<<-1<<endl;
		}
	}
	return 0;
}


posted @   unique_pursuit  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示