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)
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
Source
Southeastern Europe 2006
对树状数组的感觉真差,愣是没看出来这是求逆序数的,看了别人的博客才知道 ,ORZ
设有线段 (a,b) ,(c,d)
首先2条线段要有交点就得满足 (a-c)*(b-d)<0
所以先对左边的点从小到大排序,如果左边一样,就按右边从小到大排序,这样一来,由于左边的点一定是小到大的,所以只要统计右边序列的逆序数就行了,
至于当左边一样时得按右边从小到大排序,举个例子就知道, 1-1,1-2,这样处理的时候,当右边处理2的时候,1已经插入到树状数组,这样逆序对求出来就是2-1=1,否则不这样排序的话就会漏掉了。
树状数组真的很灵活啊,希望以后自己再给力点~~
对树状数组的感觉真差,愣是没看出来这是求逆序数的,看了别人的博客才知道 ,ORZ
设有线段 (a,b) ,(c,d)
首先2条线段要有交点就得满足 (a-c)*(b-d)<0
所以先对左边的点从小到大排序,如果左边一样,就按右边从小到大排序,这样一来,由于左边的点一定是小到大的,所以只要统计右边序列的逆序数就行了,
至于当左边一样时得按右边从小到大排序,举个例子就知道, 1-1,1-2,这样处理的时候,当右边处理2的时候,1已经插入到树状数组,这样逆序对求出来就是2-1=1,否则不这样排序的话就会漏掉了。
树状数组真的很灵活啊,希望以后自己再给力点~~
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int tree[1010];
struct node
{
int u,v;
}road[1010*1010];
int cmp(node a,node b)
{
if(a.u!=b.u)
return a.u<b.u;
return a.v<b.v;
}
inline int lowbit(int x)
{
return x&(-x);
}
void add(int x,int val)
{
for(int i=x;i<=1010;i+=lowbit(i))
tree[i]+=val;
}
__int64 sum(int x)
{
__int64 ans=0;
for(int i=x;i;i-=lowbit(i))
ans+=tree[i];
return ans;
}
int main()
{
int n,m,k,icase=1,t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d%d",&n,&m,&k);
__int64 ans=0;
memset(tree,0,sizeof(tree));
for(int i=1;i<=k;i++)
scanf("%d%d",&road[i].u,&road[i].v);
sort(road+1,road+k+1,cmp);
for(int i=1;i<=k;i++)
{
add(road[i].v,1);
ans+=i-sum(road[i].v);
}
printf("Test case %d: %I64d\n",icase++,ans);
}
return 0;
}