HDU 6237 A Simple Stone Game

A Simple Stone Game

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)

Problem Description

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

思路:

先将全部的数值相加,然后求出这个数有多少个质因子并进行记录(我用的vector记录),这些质因子实际上就是题目中的x,然后将另外设一个数组复制原来数组的全部元素,为的多次的x的石头的转移的次数的计算,石头的转移的次数计算:将复制后的数组的每个元素取模就可以发现元素的相差0或者x的值,因为总数可以与x整除,所以不存在最后会多出石头的情况,最后排序,将最大的元素与x的相差的值相加,直到将石头补齐,这个相加的值就是次数(因为每次只能取一个石头),最后比较最小值就行了,(注意:本题的极容易超时)

#include 
#include 
#include 
#include 
using namespace std;
typedef long long ll;
void isprime(vector &v, ll n) {
	for (ll i = 2; i <= sqrt(n); i++) {
		if (n % i == 0) v.push_back(i);
		while (n % i == 0) n /= i;
	}
	v.push_back(n);
}
bool cmp(ll a, ll b) {
	return a > b;
}
int main() {
	ll n, m;
	cin >> n;
	while (n--) {
		ll minn = 1e18, sum = 0;
		cin >> m;
		vector a(m), v, b(m);
		for (ll i = 0; i < m; i++) {
			cin >> a[i];
			sum += a[i];
		}
		isprime(v, sum);
		for (ll i = 0; i < v.size(); i++) {
			b = a;
			ll num = 0;
			for (ll j = 0; j < m; j++) {
				b[j] %= v[i];
				num += b[j];
			}
			ll ans = 0;
			sort(b.begin(), b.end(), cmp);
			for (ll j = 0; j < m && num > 0; j++) {
				num -= v[i];
				ans += v[i] - b[j];
			}
			minn = min(minn, ans);
		}
		cout << minn << endl;
	}
	return 0;
}

你可能感兴趣的:(HDU)