HDU-6237 A Simple Stone Game (素数筛 + 贪心)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6237

题目大意:给你N堆石子,第 i 堆石子的个数的个数为 ai,你可以对这些石子进行任意次操作,每次操作可以将第 i 堆的一个石子移动到第 j 堆(1<=i,j<=n),现在要使得N堆石子每堆石子的个数都变成一个整数 x (x > 1)的整数倍,问你最少需要进行几次操作。

题目思路:既然要使得N堆石子的每堆石子都是x的整数倍,那么这N堆石子的总石子数也会是x的整数倍,做个简单的证明,设a1 = x*b1,a2 = x * b2,...,an = x * bn,则a1 + a2 + a3 + ... +an = x * b1 +x* b2 +x* b3+ ...+x*bn = x*(b1 + b2 + b3 + ... + bn)。所以就可以先求出N堆石子总石子数sum,再将sum进行质数分解,再每次枚举sum的质因子,算出所需要移动的次数(移动的时候尽可能取数量小的石堆进行移动,这样就可以保证操作的次数尽可能少了),取最小的即是答案了。

AC代码如下:

#include <bits/stdc++.h>
#define x first
#define y second
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define fuck(x) cout<<'['<<x<<']'<<endl
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int>PII;
const int INF = 0x3f3f3f3f;
const LL INFLL = 0x3f3f3f3f3f3f3f3f;
const int MX = 1e5+7;

int prime[MX],pcnt;
bool is_prime[MX];

void prime_init(){
    for(int i = 0;i < MX;i++) is_prime[i] = true;
    pcnt = 0;
    for(int i = 2;i < MX;i++){
        if(is_prime[i])
            prime[++pcnt] = i;
        for(int j = 1;j <= pcnt;j++){
            if(prime[j]*i >= MX) break;
            is_prime[prime[j]*i] = false;
            if(i%prime[j] == 0) break;
        }
    }
}

void get_prime(LL n,vector<LL>&res){
    for(int i = 1;i <= pcnt && (LL)prime[i]*prime[i] <= n;i++){
        if(n%prime[i] == 0){
            res.push_back(prime[i]);
            while(n%prime[i] == 0){
                n /= prime[i];
            }
        }
    }
    if(n!=1)
        res.push_back(n);
}

int T,n;
LL Mod[MX];
LL a[MX];

int main(){
    prime_init();
    scanf("%d",&T);
    while(T--){
        scanf("%d",&n);
        LL sum = 0;
        for(int i = 0;i < n;i++){
            scanf("%lld",&a[i]);
            sum += a[i];
        }
        vector<LL>res;
        get_prime(sum,res);//将sum进行质数分解,将sum的质因子存在res内;
        LL ans = INFLL;
        for(int i = 0;i < res.size();i++){
            //cout << i << " " << res[i] << endl;
            for(int j = 0;j < n;j++) Mod[j] = a[j]%res[i];
            sort(Mod,Mod+n);//排序,每次移动最小的堆;
            int l = 0,r = n-1;//用双指针进行移动算操作数;
            LL tmp = 0;
            while(l < r){
                if(Mod[l] >= (res[i] - Mod[r])){
                    Mod[l] -= res[i] - Mod[r];
                    tmp += res[i] - Mod[r];
                    r--;
                } else{
                    Mod[r] += Mod[l];
                    tmp += Mod[l];
                    l++;
                }
                if(Mod[l] == 0) l++;
            }
            //cout << tmp << endl;
            ans = min(ans,tmp);
        }
        printf("%lld\n",ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值