题目:
Japan
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 26375 | Accepted: 7159 |
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
分析:
(x,y)表示一条路连接两个城市,东海岸城市坐标为x,西海岸城市坐标为y,要求出这些线路中交汇点的个数(每两条路至多一个交汇点)。两条路相交的特点为(x1-x2)*(y1-y2) < 0,即两条线段一个x大,一个y大。如果事先按照x从小到大排序,对树状数组进行单点更新时前面点的x总是小于后面的点,这时如果后面点的y小于前面的,说明产生了交点。至此问题转化为求路径y属性的逆序对。由于(1,4)和(1,3)不算相交,因此排序时也要对y按照递增序排序,否则会多算。接下来就轻车熟路了。关于树状数组求逆序对,可以参考
http://blog.csdn.net/xiaoli_nu/article/details/52718632
代码:
#include<iostream>//395ms
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<string.h>
using namespace std;
const int maxn=1010;
struct node{
int e;
int w;
}a[maxn*maxn];
int t,n,m,k,c[maxn];
bool cmp(node a,node b){
if(a.e==b.e) return a.w<b.w;
else return a.e<b.e;
}
__int64 sum(int i){//树状数组求区间和
__int64 s=0;
while(i>0){
s+=c[i];
i-=i&(-i);
}
return s;
}
void add(int i,int x){//树状数组结点值的更新
while(i<=m){//not i<=n .....注意树状数组需要开多大
c[i]+=x;
i+=i&(-i);
}
}
int main(){
scanf("%d",&t);
for(int i=1;i<=t;++i){
scanf("%d%d%d",&n,&m,&k);
for(int j=1;j<=k;++j){
scanf("%d%d",&a[j].e,&a[j].w);
}
sort(a+1,a+k+1,cmp);
memset(c,0,sizeof(c));
__int64 ans=0; //爆int
for(int j=1;j<=k;++j){
add(a[j].w,1);
ans+=j-sum(a[j].w);
}
printf("Test case %d: %I64d\n",i,ans);
}
return 0;
}