贪心的问题总是很难证明。
对于单向传递的纸牌问题:维护差值的前缀和。
https://www.luogu.com.cn/problem/P1031
#include<bits/stdc++.h> using namespace std; typedef long long LL; typedef pair<int,int> pii; const int N = 1e6+5; const int M = 1e7+5; const LL Mod = 20101009; #define pi acos(-1) #define INF 1e9 #define CT0 cin.tie(0),cout.tie(0) #define IO ios::sync_with_stdio(false) #define dbg(ax) cout << "now this num is " << ax << endl; namespace FASTIO{ inline int read() { int x = 0,f = 1;char c = getchar(); while(c < '0' || c > '9'){if(c == '-')f = -1;c = getchar();} while(c >= '0' && c <= '9'){x = (x << 1) + (x << 3) + (c ^ 48);c = getchar();} return x * f; } void print(int x){ if(x < 0){x = -x;putchar('-');} if(x > 9) print(x/10); putchar(x%10+'0'); } } using namespace FASTIO; int a[N],sum = 0; int main() { int n;n = read(); for(int i = 1;i <= n;++i) a[i] = read(),sum += a[i]; sum /= n; for(int i = 1;i <= n;++i) a[i] = a[i] - sum; int ans = 0; for(int i = 1;i <= n;++i) { if(a[i] == 0) continue; a[i + 1] += a[i]; ans++; } printf("%d ",ans); system("pause"); return 0; }
https://www.luogu.com.cn/problem/P2512
当这个问题变成环形之后,虽然可以两向传递,但是按照差值维护的思想,我们只需要传递负的价值即可。
所以就是一个单向的环问题,那么对于任意一处k断开链。
那么对于k处断开后,i位置的代价就是abs(s[i] - s[k])
那么$ans = sum_{i=1}^{N}|S[i]-S[k]$,显然当k取s的中位数时最优。
#include<bits/stdc++.h> using namespace std; typedef long long LL; typedef pair<int,int> pii; const int N = 1e6+5; const int M = 1e7+5; const LL Mod = 20101009; #define pi acos(-1) #define INF 1e9 #define CT0 cin.tie(0),cout.tie(0) #define IO ios::sync_with_stdio(false) #define dbg(ax) cout << "now this num is " << ax << endl; namespace FASTIO{ inline int read() { int x = 0,f = 1;char c = getchar(); while(c < '0' || c > '9'){if(c == '-')f = -1;c = getchar();} while(c >= '0' && c <= '9'){x = (x << 1) + (x << 3) + (c ^ 48);c = getchar();} return x * f; } void print(int x){ if(x < 0){x = -x;putchar('-');} if(x > 9) print(x/10); putchar(x%10+'0'); } } using namespace FASTIO; int a[N]; LL sum = 0; int main() { int n;n = read(); for(int i = 1;i <= n;++i) a[i] = read(),sum += a[i]; sum /= n; for(int i = 1;i <= n;++i) a[i] = a[i] - sum; for(int i = 1;i <= n;++i) a[i + 1] += a[i]; sort(a + 1,a + n + 1); LL ans = 0; if(n % 2 != 0) { int mid = n / 2 + 1; for(int i = 1;i <= n;++i) ans += abs(a[i] - a[mid]); } else { int mid1 = n / 2,mid2 = n / 2 + 1; LL ans1 = 0,ans2 = 0; for(int i = 1;i <= n;++i) ans1 += abs(a[i] - a[mid1]); for(int i = 1;i <= n;++i) ans2 += abs(a[i] - a[mid2]); ans = min(ans1,ans2); } printf("%lld ",ans); system("pause"); return 0; }