Ring evenly split card problem: Click here for details ,
The main idea: we regard it as a one-way transfer, which can be derived from the formula c[i] = s[i-1]-(i-1) * avg; the array c is the c of the warehouse location, and the median is the most Excellent solution
Code
#include<iostream>#include<cstdio>#include<string>#include<cstring>#include<algorithm>usingnamespace std;typedeflonglong ll;constint N =1e6+10;int n;
ll a[N], s[N], c[N];
ll slove(){
for(int i =1; i <= n; i++) s[i]= s[i -1]+ a[i];
ll avg = s[n]/ n;
c[1]=0;for(int i =2; i <= n; i++) c[i]= s[i -1]-(i -1)* avg;sort(c +1, c +1+ n);
ll res =0;for(int i =1; i <= n; i++) res +=abs(c[i]- c[(n +1)/2]);return res;}intmain(){
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
cin >> n;for(int i =1; i <= n; i++) cin >> a[i];
cout <<slove()<< endl;return0;}