(洛谷P2512||bzoj1045) [HAOI2008]糖果传递 || 洛谷P4016 负载平衡问题 || UVA11300 Spreading the Wealth || (洛谷P3156||bzoj3293) [CQOI2011]分金币
题解:https://www.luogu.org/blog/LittleRewriter/solution-p2512
1 #include<cstdio> 2 #include<algorithm> 3 #include<cstring> 4 #include<vector> 5 using namespace std; 6 #define fi first 7 #define se second 8 #define mp make_pair 9 #define pb push_back 10 typedef long long ll; 11 typedef unsigned long long ull; 12 typedef pair<int,int> pii; 13 int n;ll c; 14 ll a[2000100],b[2000010]; 15 ll abs1(ll x){return x>=0?x:-x;} 16 ll an; 17 int main() 18 { 19 int i;ll t; 20 while(scanf("%d",&n)==1) 21 { 22 c=0;an=0; 23 for(i=1;i<=n;++i) 24 { 25 scanf("%lld",&a[i]); 26 c+=a[i]; 27 } 28 c/=n; 29 for(i=1;i<=n;++i) 30 { 31 a[i]-=c; 32 b[i]=b[i-1]+a[i]; 33 } 34 int p=(n+1)/2; 35 nth_element(b+1,b+p,b+n+1);t=b[p]; 36 for(i=1;i<=n;++i) 37 an+=abs1(t-b[i]); 38 printf("%lld\n",an); 39 } 40 return 0; 41 }