[HAOI2008]糖果传递
规定第 i 个人只给第 i - 1个人糖果,为xi个,因为若xi < 0,说明第 i - 1个人给第 i 个人|xi|个。那么ans = |x1| + |x2| + |x3| + …… +|xn|
那么就可以列出:a1 - x1 + x2 = ave, a2 - x2 + x3 = ave, a3 - x3 + x4 = ave ……, an - xn + x1 = ave。因为从前n - 1个方程可以推导出第n 个方程(这就是为啥我把这n个方程加起来得到了恒等式……),所以只有n - 1个方程有用。
n - 1个方程n个未知数,可以用其中一个替换掉其他的未知数:x2 = ave + x1 - a1,把x2代入第二个方程得:x3 = 2 * ave + x1 - a2 - a1。令b2 = a1 - ave, b3 = a1 + a2 - 2 * ave……bn = Σan-1 - (n - 1) * ave。于是就有ans = |x1| + |x1 - b2| + |x1 - b3| + …… +|x1 - bn|。把这个看成数轴上两点之间的距离,则x1为这些数的中位数时,ans取得最小值。
于是这题完事啦。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<cstdio> 2 #include<iostream> 3 #include<cmath> 4 #include<algorithm> 5 #include<cstring> 6 #include<cstdlib> 7 #include<cctype> 8 #include<vector> 9 #include<stack> 10 #include<queue> 11 using namespace std; 12 #define enter puts("") 13 #define space putchar(' ') 14 #define Mem(a, x) memset(a, x, sizeof(a)) 15 #define rg register 16 typedef long long ll; 17 typedef double db; 18 const int INF = 0x3f3f3f3f; 19 const db eps = 1e-8; 20 const int maxn = 1e6 + 5; 21 inline ll read() 22 { 23 ll ans = 0; 24 char ch = getchar(), last = ' '; 25 while(!isdigit(ch)) {last = ch; ch = getchar();} 26 while(isdigit(ch)) {ans = ans * 10 + ch - '0'; ch = getchar();} 27 if(last == '-') ans = -ans; 28 return ans; 29 } 30 inline void write(ll x) 31 { 32 if(x < 0) x = -x, putchar('-'); 33 if(x >= 10) write(x / 10); 34 putchar(x % 10 + '0'); 35 } 36 37 int n, a[maxn]; 38 ll ave = 0, sum = 0, b[maxn]; 39 40 int main() 41 { 42 n = read(); 43 for(int i = 1; i <= n; ++i) a[i] = read(), ave += a[i]; 44 ave /= n; 45 for(int i = 2; i <= n; ++i) sum += a[i - 1], b[i] = sum - (ll)(i - 1) * ave; 46 sort(b + 1, b + n + 1); 47 ll ans = 0, x = b[n >> 1]; 48 for(int i = 1; i <= n; ++i) ans += abs(x - b[i]); 49 write(ans); enter; 50 return 0; 51 }