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

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值