【P2512 [HAOI2008]糖果傳遞】題解
阿新 • • 發佈:2021-12-05
題目連結
題目
有 \(n\) 個小朋友坐成一圈,每人有 \(a_i\) 個糖果。每人只能給左右兩人傳遞糖果。每人每次傳遞一個糖果代價為 \(1\)。
思路
設 \(x_i\) 表示第 \(i\) 個人傳給前一個人的糖果數,負數則是反向傳。
可以列出方程,然後依次把 \(x_i\) 用 \(x_1\) 表示出來,再設 \(c_i=\sum_{j=1}^{i-1}(a_j-\overline a)\),然後最終答案就是求 \(\sum |x_1-c_i|\),即讓 \(x_i\) 為 \(c\) 的中位數。
Code
// Problem: P2512 [HAOI2008]糖果傳遞 // Contest: Luogu // URL: https://www.luogu.com.cn/problem/P2512 // Memory Limit: 125 MB // Time Limit: 1000 ms // // Powered by CP Editor (https://cpeditor.org) #include<bits/stdc++.h> using namespace std; #define int long long inline int read(){int x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1; ch=getchar();}while(ch>='0'&&ch<='9'){x=(x<<1)+ (x<<3)+(ch^48);ch=getchar();}return x*f;} //#define M //#define mo //#define N struct node { int k, id; }c[1000010]; int n, m, i, j, k; int ave, ans, x_1, sum; int a[1000010]; bool cmp(node x, node y) { return x.k<y.k; } bool Cmp(node x, node y) { return x.id<y.id; } signed main() { // freopen("tiaoshi.in", "r", stdin); // freopen("tiaoshi.out", "w", stdout); n=read(); for(i=1; i<=n; ++i) a[i]=read(); for(i=1; i<=n; ++i) sum+=a[i]; ave=sum/n; sum=0; for(i=1; i<=n; ++i) { c[i].k=sum; c[i].id=i; sum+=(ave-a[i]); } sort(c+1, c+n+1, cmp); x_1=c[(n+1)/2].k; sort(c+1, c+n+1, Cmp); for(i=1; i<=n; ++i) ans+=abs(x_1-c[i].k); printf("%lld", ans); return 0; }