欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

POJ 3067 Japan(树状数组求逆序对个数)

程序员文章站 2022-05-10 15:37:01
...

POJ 3067 Japan

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的逆序数之和即为交点个数。

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int M,N,K;
long long C[1005];
typedef struct{
    int l,r;
}node;
node road[1005*1005];
bool cmp(node a,node b){
    if(a.l==b.l)
        return a.r<b.r;
    else
        return a.l<b.l;
}
int lowbit(int x){
    return x&(-x);
}
void modify(int s,int num){
    int i;
    for(i=s;i<=M;i+=lowbit(i))
        C[i]+=num;
}
long long getsum(int e){
    int i;
    long long sum=0;
    for(i=e;i>0;i-=lowbit(i))
        sum+=C[i];
    return sum;
}
int main(){
    int T;
    int i,j,k;
    long long ans;
    scanf("%d",&T);
    for(k=1;k<=T;k++){
        scanf("%d %d %d",&N,&M,&K);
        for(i=1;i<=K;i++){
            scanf("%d %d",&road[i].l,&road[i].r);
        }
        ans=0;
        sort(road+1,road+1+K,cmp);
        memset(C,0,sizeof(C));
        for(i=1;i<=K;i++){
            modify(road[i].r,1);
            ans+=(getsum(M)-getsum(road[i].r));
        }
        printf("Test case %d: %lld\n",k,ans);
    }
    return 0;
}