原题地址: http://poj.org/problem?id=3067
树状数组的典型应用,典型输入如下:
1
3 4 4
1 4
2 3
3 2
3 1
表示有4条连线,如图:
显然有5个交点。怎么求呢?对输入的数对(x,y)做排序,先按x升序排,x相等按y升序排,然后对y做树状数组,每次更新检查在他后面有多少个元素即可。
代码:
#include <iostream>
#include <algorithm>
using namespace std;
int arr[100] = {0};
struct Pair
{
int xx;
int yy;
};
int cmp(const Pair &one, const Pair &other)
{
if (one.xx < other.xx || (one.xx==other.xx && one.yy < other.yy))
return 1;
return 0;
}
int lowbit(int x)
{
return x & -x;
}
int gsum(int *p, int n, int pos)
{
int s = 0;
for (int i = pos; i>= 1; i-=lowbit(i))
s += arr[i];
return s;
}
void modify(int *p, int n, int pos, int val)
{
for (int i = pos; i<=n; i += lowbit(i) )
arr[i] += val;
}
int main()
{
int n;
cin>>n;
while(n--)
{
int x,y,m;
cin>>x>>y>>m;
Pair *pp = new Pair[m];
int i=0;
while(i<m)
{
cin>>(pp[i].xx)>>(pp[i].yy);
i++;
}
sort(pp,pp+m,cmp);
for(i=0; i<m; i++)
cout<<"连线: "<<pp[i].xx<<" "<<pp[i].yy<<endl;
int sum = 0;
for (i=0; i<m; i++)
{
modify(arr, 100, pp[i].yy, 1);
sum += (i + 1 - gsum(arr, 100, pp[i].yy) );
}
delete [] pp;
cout<<"交叉点个数: "<<sum<<endl;
}
return 0;
}
输出:
连线: 1 4
连线: 2 3
连线: 3 1
连线: 3 2
交叉点个数: 5