(rating : 1900)
D2. Half of Same
链接
https://codeforces.com/contest/1593/problem/D2
题意
给n的整数 a1,a2,a3, … ,an 。
找到一个最大的k,每次任选一个数减去k。
使得经过有限次操作以后 , 有超过半数的数字相同。
如果k任意,输出-1.
input
4
6
48 13 22 -15 16 35
8
-1 0 1 -1 0 1 -1 0
4
100 -1000 -1000 -1000
4
1 1 1 1
output
13
2
-1
-1
思路
显然,题意可以转化为,从n个数中选出 n/2 个数 ,从小到大依次为 b0 , b1 , b2 , … , bm 。
要求最大化 gcd ( b1 - b0, b2 - b0, … ,bm - b0 ) 。
那么只需要O(n) 暴力枚举选出的数中的最小值b0 , 在所有比它大的数中选出 n/2-1个与b0做差并最大化gcd就可以.
换句话说,就是求 “ m个数中选出n/2-1个数 , 最大化gcd " 。
方法是将这m个数做因数分解,把所有因数开个桶存起来 , 答案就是最大的、次数不小于n/2-1的桶。 具体见(洛谷 P1414) 。
代码
#include<bits/stdc++.h>
using namespace std;
const int N = 105;
int a[N];
const int inf = 1e9+7;
const int M = 2e6+100;
int c[M];
int n;
int main(){
ios::sync_with_stdio(false);
int t;
cin>>t;
while(t--){
cin>>n;
for(int i=1;i<=n;i++) cin>>a[i];
int ans = -1e9+7;
sort(a+1,a+1+n);
for(int i=1;i<=n;i++){
memset(c,0,sizeof c);
int cnt = 0,tt=0;
for(int j=i+1;j<=n;j++){
int x = a[j]-a[i];
if(x==0){
cnt++;
continue;
}
if(cnt+1>=n/2){
ans = inf;
break;
}
tt = max(tt,x);
int m = sqrt(x);
for(int k=1;k<=m;k++){
if(x%k==0){
c[k]++;
if(k*k!=x){
c[x/k]++;
}
}
}
}
int x = tt;
while(c[x]<n/2-cnt-1) x--;
if(x==0)
ans = inf;
else
ans = max(ans,x);
}
if(ans==inf) cout<<-1<<endl;
else cout<<ans<<endl;
}
return 0;
}