最大公约数
题意
你有一个环,环上有 n n n 个正整数。你能将环切成k段,每段包含一个或者多个数字。
对于一个切分方案,优美程度为每段数字和的最大公约数,你想使切分方案的优美程度最大,对于 k = 1 , 2 , … , n k=1,2,…,n k=1,2,…,n 输出答案。
思路
先观察一下这个样例,可以发现每段数字和的最大公因数那么一定也是这个环里所有的数加起来的和。有了这个性质,发现这个数最大才1e11的,大胆猜测一下里面最多的因子是不会超过200的
那么我们就可以根据这个已知的因子,去找关于这个因子最多能被分成几段
这里刚开始我们想的是 n 2 n^2 n2 的复杂度去枚举这段区间的开头,再暴力判断最多能被分成几段, 但这里一算复杂度,这里的复杂度已经吃不消了,这里的 n 2 n^2 n2 需要优化成 n l o g n nlogn nlogn
那这里的优化用到了一个 m a p map map , 利用前缀和的性质,把 n n n 个位置的前缀和取模当前枚举到的因子,然后出现次数最多的数量就是能分成的最大的 k k k
代码
#include<iostream>
#include<algorithm>
#include<map>
#include<stdlib.h>
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int maxn = 5000;
int b[maxn];
int a[maxn];
int sum;
int ans[maxn];
int check(int st, int ed, int x) {
int cnt = 0; int sum = 0;
for (int i = st; i <= ed; i++) {
sum += a[i];
if (sum % x == 0) cnt++, sum = 0;
}
return cnt;
}
int dp[maxn];
int pre[maxn];
int c[maxn];
void solve() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i], sum += a[i], a[i + n] = a[i], pre[i] = pre[i - 1] + a[i];
int cnt = 0;
for (int i = 2; i < sqrt(sum); i++) {
if (sum % i == 0) {
b[++cnt] = sum / i;
if (sum / i != i)b[++cnt] = i;
}
}
b[++cnt] = 1;
sort(b + 1, b + 1 + cnt);
for (int i = cnt; i >= 1; i--) {
map<int, int>mp;
for (int j = 1; j <= n; j++) {
mp[pre[j] % b[i]]++;
}
int maxx = 0;
for (auto x : mp) {
maxx = max(x.second, maxx);
}
ans[i] = maxx;
}
for (int i = 1; i <= cnt; i++) {
for (int j = 1; j <= n; j++) {
if (ans[i] >= j) dp[j] = max(b[i], dp[j]);
}
}
dp[1] = sum;
for (int i = 1; i <= n; i++) {
cout << dp[i] << endl;
}
}
signed main() {
solve();
return 0;
}