https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=4174
1 #include<iostream> 2 #include<cstring> 3 #include<algorithm> 4 #include<vector> 5 using namespace std; 6 #define lowbit(x) ((x)&(-x)) 7 typedef long long LL; 8 const int maxn = 100000 + 10; 9 int a[maxn],s[maxn]; 10 LL b[maxn]; 11 int iNum; 12 13 void add(int x,int v) 14 { 15 while (x<=iNum) 16 { 17 s[x]+=v; 18 x += lowbit(x); 19 } 20 21 } 22 23 int sum (int x) 24 { 25 int ret = 0; 26 while (x>0) 27 { 28 ret += s[x]; 29 x -= lowbit(x); 30 } 31 return ret; 32 } 33 int main() 34 { 35 36 int T; 37 cin >> T; 38 while (T--) 39 { 40 int n; 41 cin >> n; 42 memset(s, 0, sizeof(s)); 43 for (int i = 1;i<=n;i++) 44 { 45 46 cin >> a[i]; 47 48 iNum = max(iNum,a[i]); 49 } 50 51 52 for (int i = 1;i<=n;i++) 53 { 54 55 b[i] = sum(a[i]-1); 56 add(a[i],1); 57 } 58 LL ans = 0; 59 memset(s,0,sizeof(s)); 60 for (int i = n;i>0;i--) 61 { 62 LL d = sum(a[i]-1); 63 add(a[i],1); 64 ans += (b[i] * (n - i - d)) + d * (i - 1 - b[i]); 65 66 } 67 cout << ans << endl; 68 } 69 return 0; 70 }
时间: 2024-10-12 11:32:13