Description
Japan plans to welcome the ACM ICPC World Finals and a lot of roads must be built for the venue. Japan is tall island with N cities on the East coast and M cities on the West coast (M <= 1000, N <= 1000). K superhighways will be build. Cities on each coast are numbered 1, 2, … from North to South. Each superhighway is straight line and connects city on the East coast with city of the West coast. The funding for the construction is guaranteed by ACM. A major portion of the sum is determined by the number of crossings between superhighways. At most two superhighways cross at one location. Write a program that calculates the number of the crossings between superhighways.
Input
The input file starts with T - the number of test cases. Each test case starts with three numbers – N, M, K. Each of the next K lines contains two numbers – the numbers of cities connected by the superhighway. The first one is the number of the city on the East coast and second one is the number of the city of the West coast.
Output
For each test case write one line on the standard output:
Test case (case number): (number of crossings)
Sample Input
1
3 4 4
1 4
2 3
3 2
3 1
Sample Output
Test case 1: 5
题意:日本岛东海岸与西海岸分别有N和M个城市,现在修高速公路连接东西海岸的城市,求交点个数。
做法:记每条告诉公路为(x,y), 即东岸的第x个城市与西岸的第y个城市修一条路。当两条路有交点时,满足(x1-x2)*(y1-y2) < 0。所以,将每条路按x从小到达排序,若x相同,按y从小到大排序。 然后按排序后的公路用树状数组在线更新,求y的逆序数之和,即为交点个数。
用树状数组求逆序对,逆序对的个数就是,对于每一个数统计前面比它大的数出现次数之和,树状数组维护当前的值出现过几次,每个数a[i[,逆序对为getsum(m)-getsum(a[i[).
总觉得cin迷之有坑,改用scanf。
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int t,p,n,m,k,c[1005];
long long ans;
struct edge
{
int x,y;
}a[1000005];
bool cmp(edge c,edge d)
{
if(c.x==d.x)
return c.y<=d.y;
return c.x<d.x;
}
int lowbit(int x)
{
return x&(-x);
}
void add(int pos,int x)
{
while(pos<=m)
{
c[pos]+=x;
pos+=lowbit(pos);
}
}
int getsum(int pos)
{
int sum=0;
while(pos)
{
sum+=c[pos];
pos-=lowbit(pos);
}
return sum;
}
int main()
{
scanf("%d",&t);
while(t--)
{
ans=0;
memset(c,0,sizeof(c));
scanf("%d%d%d",&n,&m,&k);
for(int i=1;i<=k;i++)
scanf("%d%d",&a[i].x,&a[i].y);
sort(a+1,a+k+1,cmp);
for(int i=1;i<=k;i++)
{
ans+=getsum(m)-getsum(a[i].y);
add(a[i].y,1);
}
printf("Test case %d: %lld\n",++p,ans);
}
return 0;
}