POJ3067——Japan

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

Source

Southeastern Europe 2006


对树状数组的感觉真差,愣是没看出来这是求逆序数的,看了别人的博客才知道 ,ORZ


设有线段   (a,b)   ,(c,d)
首先2条线段要有交点就得满足   (a-c)*(b-d)<0

所以先对左边的点从小到大排序,如果左边一样,就按右边从小到大排序,这样一来,由于左边的点一定是小到大的,所以只要统计右边序列的逆序数就行了,
至于当左边一样时得按右边从小到大排序,举个例子就知道,  1-1,1-2,这样处理的时候,当右边处理2的时候,1已经插入到树状数组,这样逆序对求出来就是2-1=1,否则不这样排序的话就会漏掉了。

树状数组真的很灵活啊,希望以后自己再给力点~~

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>

using namespace std;

int tree[1010];
struct node
{
	int u,v;
}road[1010*1010];

int cmp(node a,node b)
{
	if(a.u!=b.u)
		return a.u<b.u;
	return a.v<b.v;
}

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

void add(int x,int val)
{
	for(int i=x;i<=1010;i+=lowbit(i))
		tree[i]+=val;
}

__int64 sum(int x)
{
	__int64 ans=0;
	for(int i=x;i;i-=lowbit(i))
		ans+=tree[i];
	return ans;
}

int main()
{
	int n,m,k,icase=1,t;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d%d%d",&n,&m,&k);
		__int64 ans=0;
		memset(tree,0,sizeof(tree));
		for(int i=1;i<=k;i++)
			scanf("%d%d",&road[i].u,&road[i].v);
		sort(road+1,road+k+1,cmp);
		for(int i=1;i<=k;i++)
		{
			add(road[i].v,1);
			ans+=i-sum(road[i].v);
		}
		printf("Test case %d: %I64d\n",icase++,ans);
	}
	return 0;
}





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值