原题链接https://codeforces.com/contest/1593/problem/D2
D2. Half of Same
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
This problem is a complicated version of D1, but it has significant differences, so read the whole statement.
Polycarp has an array of nn (nn is even) integers a1,a2,…,ana1,a2,…,an. Polycarp conceived of a positive integer kk. After that, Polycarp began performing the following operations on the array: take an index ii (1≤i≤n1≤i≤n) and reduce the number aiai by kk.
After Polycarp performed some (possibly zero) number of such operations, it turned out that at least half of the numbers in the array became the same. Find the maximum kk at which such a situation is possible, or print −1−1 if such a number can be arbitrarily large.
Input
The first line contains one integer tt (1≤t≤101≤t≤10) — the number of test cases. Then tt test cases follow.
Each test case consists of two lines. The first line contains an even integer nn (4≤n≤404≤n≤40) (nn is even). The second line contains nn integers a1,a2,…ana1,a2,…an (−106≤ai≤106−106≤ai≤106).
It is guaranteed that the sum of all nn specified in the given test cases does not exceed 100100.
Output
For each test case output on a separate line an integer kk (k≥1k≥1) — the maximum possible number that Polycarp used in operations on the array, or −1−1, if such a number can be arbitrarily large.
Example
input
Copy
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
Copy
13 2 -1 -1
-------------------------------------------------------------------------------------------------------------------
可以根据上一题推断,如果有超过n/2元素相同,那么k可以取任意值
上一题是求n个数和最小值的差值
本题想要构造出n/2个,那么n/2个元素和其最小值差距也必须是k的倍数
一种方法是,我们可以枚举n/2个数,然后按照第一题方法写,显然会超时
另一种方法,我们枚举最小值,计算剩余数与它的差值,然后取最大gcd,然而这种做法求得的是
剩余n-i个元素和最小值的差,随着元素个数增加,gcd会减小,而我们只需要n/2个元素就够,显然这样做又难以避免枚举n/2个数
比较好的做法是,枚举最小值a[i],计算每一个比它大的元素的差值,提取这个差值的因子,如果这个因子是n/2-1个数与a[i]的差值,那么显然这个k满足条件,并且我们记录k的最大值即可
# include<iostream>
# include<map>
# include<algorithm>
using namespace std;
typedef long long int ll;
map<int,int>m;
int a[110],n;
bool check(int factor,int pos)
{
int cnt=0;
for(int i=pos+1;i<=n;i++)
{
if((a[i]-a[pos])%factor==0)
cnt++;
}
if(cnt>=n/2-1)
return 1;
return 0;
}
int main ()
{
int t;
cin>>t;
while(t--)
{
int flag=0;
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i];
m[a[i]]++;
if(m[a[i]]>=n/2)
flag=1;
}
m.clear();
if(flag)
{
cout<<-1<<'\n';
continue;
}
sort(a+1,a+1+n);
int ans=0;
for(int i=1;i<=n;i++)
{
for(int j=i+1;j<=n;j++)
{
int cha=a[j]-a[i];
for(int k=1;k*k<=cha;k++)
{
if(cha%k==0)
{
if(check(k,i))
ans=max(ans,k);
if(check(cha/k,i))
ans=max(ans,cha/k);
}
}
}
}
cout<<ans<<'\n';
}
return 0;
}