hdu 2838 Cow Sorting
题意:
给出一个数组,要求把他们排成升序,两个数字交换的代价是x + y,求代价的总和。
思路:
简单的逆序对变形,树状数组维护小于的cnt和sum即可。
代码:
1 #include <stdio.h> 2 #include <string.h> 3 #include <algorithm> 4 using namespace std; 5 typedef long long ll; 6 const int N = 1e5 + 10; 7 const int M = 100000; 8 int a[N]; 9 int c[N]; 10 ll sum[N]; 11 int lowbit(int x) 12 { 13 return x&(-x); 14 } 15 void addcnt(int x) 16 { 17 for (int i = x;i <= M;i += lowbit(i)) c[i]++; 18 } 19 int getcnt(int x) 20 { 21 int ans = 0; 22 for (int i = x;i > 0;i -= lowbit(i)) ans += c[i]; 23 return ans; 24 } 25 void addsum(int x,int y) 26 { 27 for (int i = x;i <= M;i += lowbit(i)) sum[i] += y; 28 } 29 ll getsum(int x) 30 { 31 ll ans = 0; 32 for (int i = x;i > 0;i -= lowbit(i)) ans += sum[i]; 33 return ans; 34 } 35 int main() 36 { 37 int n; 38 while (scanf("%d",&n) != EOF) 39 { 40 memset(c,0,sizeof(c)); 41 memset(sum,0,sizeof(sum)); 42 for (int i = 0;i < n;i++) 43 { 44 scanf("%d",&a[i]); 45 } 46 ll tmp = 0; 47 ll ans = 0; 48 for (int i = 0;i < n;i++) 49 { 50 int cnt = getcnt(a[i]); 51 cnt = i - cnt; 52 ll s = getsum(a[i]); 53 s = tmp - s; 54 ans += s + 1LL * cnt * a[i]; 55 addcnt(a[i]); 56 addsum(a[i],a[i]); 57 tmp += a[i]; 58 } 59 printf("%lld\n",ans); 60 } 61 return 0; 62 }
康复训练中~欢迎交流!