HDU 6237 题解
题目大意
有 \(n\) 堆石子,每次可以任意从其中一个移动到另一个上,算作一次操作。结束状态是对于当前所有石子堆个数,存在一个公因子 \(x\) 且 \(x>1\),问可能的最少步数。
题解
我们先去考虑一下最终状态会是什么样子,设最终每一个石子堆个数变为 \(c[i]\),存在 \(x>1\) 使得 \(x\mid c[i]\) 对任意 \(i\) 成立,我么就会有: \[
x\mid c[1]+c[2]+\cdots+c[n]
\] 设\(s=\displaystyle \sum_{i=1}^{n}{c[i]}\),由于每次操作不会改变总数,则初始状态的和依然为 \(s\),所以我们发现,\(x\) 一定是 \(s\) 的因数,故我们把初始的 \(a[i]\) 求和得到 \(s\) ,便可以对其质因数分解,只用在这些质因数里枚举就可以了。
假设枚举到 \(s\) 的质因数 \(x\),由于只需要是 \(x\) 的倍数,所以我们考虑 \(x\) 的同余系,对 \(a[i]\) 每个数取模 \(x\),由于保证答案一定存在,我们计算取余后的数组和 \(t\),则最终需要“凑整”的堆数即为 \(\displaystyle k=\frac{t}{c}\),把取模后的数组排序,取前 \(k\) 大的补全为 \(x\)(从末尾比较小的补过去),更新得到最小的步数即为答案。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| #include <cstdio> #include <cctype> #include <algorithm> #include <cstring> #include <iostream> #include <vector> #include <cassert> #include <cmath> using namespace std; typedef long long ll; template <typename _Tp> void read(_Tp &a, char c = 0, int f = 1) { for(c = getchar(); !isdigit(c); c = getchar()) if(c == '-') f = -1; for(a = 0; isdigit(c); a = a * 10 + c - '0', c = getchar()); a *= f; } template <typename _Tp> void write(_Tp a) { if(a < 0) putchar('-'), a = -a; if(a > 9) write(a / 10); putchar(a % 10 + '0'); }
const int N = 1e5 + 5;
bool vis[N]; int p[N], tot;
void sieve(int n) { memset(vis, 0, sizeof(vis)); for(int i = 2; i <= n; i++) { if(!vis[i]) { p[++tot] = i; } for(int j = 1; j <= tot && i * p[j] <= n; j++) { vis[i * p[j]] = 1; if(i % p[j] == 0) break; } } }
int n, a[N], c[N];
int main() { sieve(1e5 + 5); int T; read(T); while(T--) { read(n); ll s = 0; for(int i = 1; i <= n; i++) { read(a[i]); s += a[i]; } vector<ll> b; ll _s = s; for(int i = 1; p[i] <= s / p[i] && i <= tot; i++) { if(s % p[i] == 0) { b.push_back(p[i]); while(s % p[i] == 0) { s /= p[i]; } } } if(s > 1) { b.push_back(s); } ll _ans = 1e10; for(auto x : b) { ll t = 0; for(int i = 1; i <= n; i++) { c[i] = a[i] % x; t += c[i]; } ll k = t / x; assert(t % x == 0); sort(c + 1, c + n + 1, greater<int>()); ll ans = 0; for(int i = 1; i <= k; i++) { ans += x - c[i]; } _ans = min(ans, _ans); } write(_ans), putchar('\n'); } return 0; }
|