HDU - 6237 - A Simple Stone Game( 分解质因子)

HDU - 6237 - A Simple Stone Game( 分解质因子)

After he has learned how to play Nim game, Bob begins to try another stone game which seems much easier.

The game goes like this: one player starts the game with N piles of stones. There is ai stones on the ith pile. On one turn, the player can move exactly one stone from one pile to another pile. After one turn, if there exits a number x(x>1) such that for each pile bi is the multiple of x where bi is the number of stone of the this pile now), the game will stop. Now you need to help Bob to calculate the minimum turns he need to stop this boring game. You can regard that 0 is the multiple of any positive number.
Input
The first line is the number of test cases. For each test case, the first line contains one positive number N(1≤N≤100000), indicating the number of piles of stones.

The second line contains N positive number, the ith number ai(1≤ai≤100000) indicating the number of stones of the ith pile.

The sum of N of all test cases is not exceed 5∗105.
Output
For each test case, output a integer donating the answer as described above. If there exist a satisfied number x initially, you just need to output 0. It’s guaranteed that there exists at least one solution.
Sample Input
2
5
1 2 3 4 5
2
5 7
Sample Output
2
1

题目大意:

有n堆石头,每堆石头有ai个,每次操作可以把一堆石头的1个移动到另一堆上。
问:最少需要多少次操作才能让这n堆石头的个数都是x的倍数 (只要存在这么一个x就行)

解题思路:

每一堆都得是x的倍数 那么如果总共有sum个,那么这个x一定是sum的因子。
因为 8和4 都是2的倍数,所以只要考虑质因子就够了

所以可以把石头总数sum分解质因子,然后对这些挨个尝试这个质因子作为这个x 所需要的最小操作数,找个最小的

如何判断这个最小操作数呢?我们只要把每一堆石头都取余这个x,余数和记作sum1,这样得出来的结果s就是比是x的倍数多s 或者少(x-s)个。所以我们把这个结果从大到小排个序,这样余数大的补成x.一直补,补一个让sum1-x 一直到sum1减到0就说明已经把所有的数都补成或者拿点一部分 变成x的倍数了。

AC代码:

#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn = 1e5+10;
set<ll> s;
ll a[maxn];
int n;
void find(ll x){
	for(ll i=2;i*i<=x;i++){
		if(x%i==0){
			s.insert(i);
			while(x%i==0){
				x/=i;
			}
		}
	}
	if(x>1) s.insert(x);
	return ;
}
bool cmp(ll x,ll y){
	return x>y;
}
int main(){
	int t;
	cin>>t;
	while(t--){
		scanf("%d",&n);
		s.clear();
		ll sum_num =0;
		for(int i=1;i<=n;i++){
			scanf("%lld",&a[i]);
			sum_num += a[i];
		}
		find(sum_num);
		ll ans = 1e18;
		set<ll>::iterator it;
		for(it = s.begin();it!=s.end();it++){
			ll now = *it;
			ll sum = 0;
			vector<ll> ve;
			for(int i=1;i<=n;i++){
				ll tmp = a[i]%now;
				if(tmp==0) continue;
				else{
					ve.push_back(tmp);
					sum+=tmp;
				}
			}
			sort(ve.begin(),ve.end(),cmp);
			ll time = 0;
			for(int i=0;i<ve.size();i++){
				ll tt = ve[i];
				sum -= now;
				time+=(now-tt);
				if(sum<=0) break;
			}
			ans = min(ans,time);
		}
		printf("%lld\n",ans);
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值