Moo Volume POJ - 2231
考察:递推
思路:
设f[i]是i与其他牛的噪音和,我们可以发现它与f[i+1]的关系是f[i+1] = f[i]+i*d-(n-i)*d(d为与i+1的距离).实际是指f[i+1]比f[i]多i个d的距离,而f[i]又比f[i+1]多计算了(n-i)个距离.
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 using namespace std; 6 typedef long long LL; 7 const int N = 10010; 8 LL f[N],a[N]; 9 int main() 10 { 11 int n; 12 scanf("%d",&n); 13 for(int i=1;i<=n;i++) scanf("%d",&a[i]); 14 sort(a+1,a+n+1); 15 for(int i=2;i<=n;i++) f[1]+=a[i]-a[1]; 16 LL ans = f[1]; 17 for(int i=1;i<n;i++) 18 { 19 LL d= a[i+1]-a[i]; 20 f[i+1] = f[i]-(n-i)*d+i*d; 21 ans+=f[i+1]; 22 } 23 printf("%lld\n",ans); 24 return 0; 25 }