F. Kuroni and the Punishment(最少操作使gcd>1 概率问题 想法)

http://codeforces.com/problemset/problem/1305/F

题意:

有n个数,每次操作可以使某个数加一或者减一,使gcd>1的最少操作数量

解析:

我们可以O(n)求出,调整最后gcd为素数P的倍数的最少操作数。问题是这个P。

由于素数2的存在,我们可以得出操作数至多为n。

考虑现在将n个操作分配给n个数,所以可以得出结论:至少存在n/2个数,其最后变为 i , i + 1 , i 1 i,i+1,i-1 (n/2个加减2,n/2个不动)

也就是说,随便从n个数里面选择一个数 a i a_i a i , a i + 1 , a i 1 a_i,a_i+1,a_i-1 的因子中存在最后答案素数 P P 的概率为1/2。

代码:

/*
 *  Author : Jk_Chen
 *    Date : 2020-03-05-10.35.26
 */
#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define rep(i,a,b) for(int i=(int)(a);i<=(int)(b);i++)
#define per(i,a,b) for(int i=(int)(a);i>=(int)(b);i--)
#define mmm(a,b) memset(a,b,sizeof(a))
#define pb push_back
#define pill pair<int, int>
#define fi first
#define se second
#define debug(x) cerr<<#x<<" = "<<x<<'\n'
const LL mod=1e9+7;
const int maxn=2e5+9;
const int inf=0x3f3f3f3f;
LL rd(){ LL ans=0; char last=' ',ch=getchar();
    while(!(ch>='0' && ch<='9'))last=ch,ch=getchar();
    while(ch>='0' && ch<='9')ans=ans*10+ch-'0',ch=getchar();
    if(last=='-')ans=-ans; return ans;
}
#define rd rd()
/*_________________________________________________________begin*/

LL a[maxn];
vector<LL>V;

void deal(LL p){
    if(p<2)return;
    LL ms=sqrt(p)+1;
    rep(i,2,ms){
        if(p%i==0)V.pb(i);
        while(p%i==0)p/=i;
    }
    if(p>1)V.pb(p);
}

int main(){
    int n=rd;
    rep(i,1,n)a[i]=rd;
    shuffle(a+1,a+1+n,default_random_engine (time(0)));
    rep(i,1,min(n,50)){
        deal(a[i]);
        deal(a[i]+1);
        deal(a[i]-1);
    }
    sort(V.begin(),V.end());
    V.erase(unique(V.begin(),V.end()),V.end());
    LL ans=2e18;
    for(auto P:V){
        LL sum=0;
        rep(i,1,n){
            LL b=a[i]/P*P;
            if(b==0)b=P;
            sum+=min(abs(a[i]-b),abs(b+P-a[i]));
        }
        ans=min(ans,sum);
    }
    printf("%lld\n",ans);
    return 0;
}

/*_________________________________________________________end*/

发布了773 篇原创文章 · 获赞 345 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/jk_chen_acmer/article/details/104677108
今日推荐