ime Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 32653 | Accepted: 8776 |
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个城市之间形成的交叉路口的数量。因为如果(x1-x2)*(y1-y2)<0的话那么东边的城市x1与西边的城市y1形成的高速公路和东边的城市x2与西边的城市y2形成的高速公路之间有交叉路口。那么我们可以先将东边的城市从小到大排序然后再判断如果x相等的话那么y从小到大排序,因为若x相等则两条公路之间不会有交叉路口。只要交y的逆序数求出来即可得到最终答案。因为这道题的数据不大,可以直接用query(m)-query(a[i].y)。
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
#define ll long long
using namespace std;
int n,k,m;
struct pp
{
int x,y;
} a[1005*1005];
bool cmp(pp a,pp b)
{
if(a.x==b.x)return a.y<=b.y;
return a.x<b.x;
}
ll s[1005];
int lowbit(int i)
{
return i&(-i);
}
void modify(int x,int y)
{
while(x<=m)
{
s[x]+=y;
x+=lowbit(x);
}
}
int query(int x)
{
ll sum=0;
while(x)
{
sum+=s[x];
x-=lowbit(x);
}
return sum;
}
int main()
{
int q,cont=0;
scanf("%d",&q);
while(q--)
{
memset(s,0,sizeof(s));
scanf("%d%d%d",&k,&m,&n);
for(int i=1; i<=n; i++)
{
scanf("%d%d",&a[i].x,&a[i].y);
}
sort(a+1,a+n+1,cmp);
ll ans=0;
for(int i=1;i<=n;i++)
{
modify(a[i].y,1);
ans+=(query(m)-query(a[i].y));
}
printf("Test case %d: %lld\n",++cont,ans);
}
}