2021-10-18 Codeforces Round #748 (Div. 3) D2. Half of Same (数学)

12 篇文章 0 订阅
4 篇文章 0 订阅

(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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值