树状数组的wiki页面:http://zh.wikipedia.org/wiki/%E6%A0%91%E7%8A%B6%E6%95%B0%E7%BB%84
题意:给出士兵的身高站位求逆序数,本题中是求某人前面比他矮的人的个数和。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 10007;
int c[N], n;
int lowbit(int i)
{
return i&(-i);
}
void add(int i, int val)
{
while(i <= n)
{
c[i] += val;
i += lowbit(i);
}
}
int sum(int i)
{
int s = 0;
while(i > 0)
{
s += c[i];
i -= lowbit(i);
}
return s;
}
int main()
{
int k, s, max, i, j, x, max_f;
while(~scanf("%d%d", &n, &k))
{
max = 0; max_f = 1;
for(i = 0; i < k; i++)
{
memset(c, 0, sizeof(c));
for(s = 0, j = 0; j < n; j++)
{
scanf("%d", &x);
x = n - x + 1;
add(x, 1);
s += sum(x-1);
}
if(s > max) {max = s; max_f = i+1;}
}
cout << max_f << endl;
}
return 0;
}