问题 C: Count Inversions
时间限制: 1 Sec 内存限制: 128 MB
提交: 36 解决: 15
[提交][状态][讨论版][命题人:外部导入]
题目描述
给一个数组,算inverted pair的数目
输入
有多组测试样例。每组输入数据占一行,每一行是一个数组,数组之间的元素用空格分开
输出
每组输出结果占一行。对应于每组输入数据的inversions
样例输入
1 2 3 2 1 3 3 2 1
样例输出
0 1 3
#include<iostream>//树状数组解法
#include<string>
#include<cstring>
#include<cstdio>
using namespace std;
#define lowbit(i) ((i)&(-i))
int a[100050], c[100050], n, num;
string s;
void update(int x, int v) {
for (int i = x; i < 1e5; i += lowbit(i)) {
c[i] += v;
}
}
int getSum(int x) {
int sum = 0;
for (int i = x; i > 0; i -= lowbit(i)) {
sum += c[i];
}
return sum;
}
int main(){
while (getline(cin, s)) {
n = num = 0;
memset(c, 0, sizeof(c));
memset(a, 0, sizeof(a));
while (s.length()){
int pos = s.find(" ");
if (pos == string::npos){
sscanf(s.c_str(), "%d", &a[n++]);
break;
}
else sscanf(s.substr(0, pos).c_str(), "%d", &a[n++]);
s.erase(0, pos + 1);
}
for (int i = 0; i < n; i++) {
update(a[i], 1);
num += getSum(1e5) - getSum(a[i]);
}
cout << num << endl;
}
return 0;
}