POJ 3067 Japan

Description

Japan plans to welcome the ACMICPC World Finals and a lot of roads must be built for the venue. Japan is tallisland 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 arenumbered 1, 2, ... from North to South. Each superhighway is straight line andconnects city on the East coast with city of the West coast. The funding forthe construction is guaranteed by ACM. A major portion of the sum is determinedby the number of crossings between superhighways. At most two superhighwayscross at one location. Write a program that calculates the number of thecrossings 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 connectedby the superhighway. The first one is the number of the city on the East coastand second one is the number of the city of the West coast.

Output

For each test case write oneline 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个城市,城市都一次竖直排列。有K条高速公路,告诉每条路连接的两个城市。现在求这些高速公路有多少个交点。

 

解题思路:可以先将道路按左边城市升序排列,左边相同时,按右边升序排列。问题就转化为排序后,道路右边城市排列的逆序数。

 

方法:树状数组。

j-1表示已经处理了多少条路。sum(x)表示x之前小于x的数的个数。(j-1)- sum(x)即为x之前大于x的数的个数。

 

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
using namespace std;

int C[1010], N, M, K;

struct node
{
	int a,b;
}path[1000010];

bool cmp(node x, node y)
{
	if(x.a==y.a)
	{
		return x.b<y.b;
	}
	return x.a<y.a;
};

int lowbit(int x)
{
    return x&(-x);
};

void update(int x, int val)
{
    for(int i=x;i<=M;i+=lowbit(i))
    {
        C[i] += val;
    }
};

int sum(int x)
{
    int temp=0;
    for(int i=x;i>=1;i-=lowbit(i))
    {
        temp += C[i];
    }
    return temp;
};

int main()
{
	int T;
	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",&path[j].a,&path[j].b);
		}

		sort(path+1,path+1+K,cmp);
		memset(C,0,sizeof(C));
		long long ans = 0;
		for(int j = 1;j<=K;j++)
		{
			ans += ((j - 1) - sum(path[j].b));
			update(path[j].b,1);
		}
		printf("Test case %d: %I64d\n",i,ans);
	}
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值