Problem: 2299 User: shu_dayang Memory: 7380K Time: 500MS Language: C++ Result: Accepted Source Code//树状数组 #include<iostream> #include<cstring> #include<cstdio> #include<algorithm> typedef long long LL; #define MAXN 500005 #define MID(l,r) ((l + r) >> 1) using namespace std; int c[MAXN],aa[MAXN]; int n; struct Node { int val; int order; }a[MAXN]; bool cmp(Node a, Node b) { return a.val < b.val; } int lowbit(int x) { return x &(-x); } void update(int x) { while(x <= n) { c[x] += 1; x += lowbit(x); } } int query(int x) { int sum = 0; while(x > 0) { sum += c[x]; x -= lowbit(x); } return sum; } int main() { LL ans; while(~scanf("%d",&n) && n != 0) { memset(c,0,sizeof(c)); for(int i = 1; i <= n; i++) { scanf("%d",&a[i].val); a[i].order = i; } sort(a+1,a+1+n,cmp); for(int i = 1; i <= n; i++) aa[a[i].order] = i; ans = 0; for(int i = 1; i <= n; i++) { update(aa[i]); ans += i - query(aa[i]); } printf("%I64d\n",ans); } return 0; }
时间: 2024-11-03 01:25:23