利用树状数组和线段树都可以求解逆序数,树状数组代码量更小一些,学这个先
给个链接,传送门 : 树状数组求逆序数,写的还可以,给定的代码中有一个地方写错了,应该是ans += i - getsum(a)而不是ans+=i-insert(a),给出一些详细的解释,如果每一个数都是按顺序(全排列)放入树状数组里的话,每个数对应的 i - getsum(a)都是零,最后求出的ans必然是零,这个是关键所在很重要自己体会,如果不是按顺序放入,错位的数就会有新的非零值,求出的ans即逆序数值
Japan这道题就是利用逆序数进行求解,设每个东海岸城市坐标为x,对应的西海岸城市坐标为y,若满足(x1-x2)*(y1-y2)<0,两条路才有交点,求交点总个数,我们如果保证x按照升序排列,即(x1-x2)<0,题意就变成了求关于y的逆序数((y1-y2)>0),
题目链接:POJ - 3067
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<cmath>
using namespace std;
int n, m, k;
struct node
{
int x, y;
}a[1002 * 1002];
int c[1005];
bool cmp(node a, node b)
{
if(a.x == b.x)
return a.y < b.y;
else return a.x < b.x;
}
int lowbit(int x)
{
return x & (-x);
}
void update(int n, int num)
{
while(n <= 1005)
{
c[n] += num;
n += lowbit(n);
}
}
int getsum(int x)
{
int ans = 0;
while(x > 0)
{
ans += c[x];
x -= lowbit(x);
}
return ans;
}
int main()
{
int t;
int cas = 1;
scanf("%d",&t);
while(t --)
{
memset(c, 0, sizeof(c));
scanf("%d%d%d",&n,&m,&k);
for(int i = 0; i < k; i ++)
{
scanf("%d%d",&a[i].x, &a[i].y);
}
sort(a, a + k, cmp);
long long ans = 0;
for(int i = 0; i < k; i ++)
{
update(a[i].y, 1);//每次都+1
ans += (i + 1) - getsum(a[i].y);
}
printf("Test case %d: %lld\n",cas ++,ans);
}
return 0;
}