/*樹狀數組求解逆序對 (1)對數據進行離散化 (2)構建樹狀數組求解逆序對*/
// poj2299逆序對_樹狀數組.cpp : 定義控制檯應用程序的入口點。#include "stdafx.h"#include <stdio.h>#include <algorithm>using namespace std;const int N = 500003;typedef struct Node{int value;int no;int tag;}Node;Node node[N], oriNode[N];int n;int sub[N];bool cmp1(Node m1, Node m2){return m1.value < m2.value;}bool cmp2(Node m1, Node m2){return m1.tag < m2.tag;}void serialize(){sort(node + 1, node + n + 1, cmp1);int cnt = 1;node[1].no = 1;for(int i = 2; i <= n; i++){if(node[i].value != node[i - 1].value)node[i].no = ++cnt;elsenode[i].no = node[i - 1].no;}sort(node + 1, node + n + 1, cmp2);}int lowbit(int x){return x & (-x);}void update(int pos, int inc){while(pos <= n){sub[pos] += inc;pos += lowbit(pos);}}int sum(int pos){int ret = 0;while(pos > 0){ret += sub[pos];pos -= lowbit(pos);}return ret;}int main(){while(~scanf("%d", &n) && n){memset(sub, 0, sizeof(sub));for(int i = 1; i <= n; i++){scanf("%d", &node[i].value);node[i].tag = i;}serialize();long long ans = 0;for(int i = 1; i <= n; i++){update(node[i].no, 1);ans += i - sum(node[i].no);}printf("%lld\n", ans);}return 0;}