hdoj 6237 A Simple Stone Game

11 篇文章 0 订阅

题目链接:A Simple Stone Game

题目大意:有n堆石头,你每次可以将一堆石头里面的一个移动到另一堆里面,问最少需要多少次可以使得所有石头堆的数量都可以被某一个数整除

题目思路:因为我们只能移动石头,所以所有石头堆的总数一定是固定的,所以最后找到的数一定是总数的某一个因子,然后枚举每一个素因子,然后找这个素因子需要移动的数量,我们只需要对这个素因子求余然后从大到小排序然后对每个石头堆补完素数因子就好了(因为要移动的石头最少,所以补大的,而且剩下的总和一定是这个素因子的倍数,那么一定能补完),然后找所有素因子里面最小的移动步数就好了

时间复杂度&&空间复杂度:O(2n*cnt)&&O(n)(cnt为素因子个数)



#include <map>
#include <set>
#include <cmath>
#include <vector>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>

using namespace std;
typedef long long ll;
const int maxn = 5e5+10;

ll a[maxn],phi[maxn],mo[maxn];
ll sum,cnt;

bool cmp(ll a,ll b){return a > b;}

void init(){
    cnt = 0;
    for(ll i = 2;i*i <= sum;i++){
        if(sum%i == 0) phi[cnt++] = i;
        while(sum%i == 0) sum /= i;
    }
    phi[cnt++] = sum;
}

int main(){
    ll T,n,minn,num;
    scanf("%lld",&T);
    while(T--){
        scanf("%lld",&n);
        sum = 0;
        for(ll i = 0;i < n;i++){
            scanf("%lld",&a[i]);
            sum += a[i];
        }
        init();
        minn = 1e10+10;
        for(ll j = 0;j < cnt;j++){
            num = 0;
            for(ll i = 0;i < n;i++) mo[i] = a[i]%phi[j],num += mo[i];
            ll ret = 0;
            sort(mo,mo+n,cmp);
            ll i = 0;
            while(num > 0&&i < n){
                ret += phi[j]-mo[i];
                num -= phi[j];
                i++;
            }
            minn = min(minn,ret);
        }
        printf("%lld\n",minn);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值