poj-3067-Japan(树状数组,逆序数)

题目链接:http://poj.org/problem?id=3067

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

题目大意:左边n个城市,右边m个城市,城市之间有k条连接的道路,对于每条道路,都可能会与其他道路有交叉口

交叉口不会重合,问总共有多少个交叉口

按照要求,满足条件:(a.c1>b.c1&&a.c2<b.c2)||(a.c1<b.c1&&a.c2>b.c2)即为一个交叉口

第一优先级:右边的城市升序排列,第二优先级:左边的城市升序,那么,按顺序遍历右边的城市,因为左边的城市升序,那么只用找该城市对之前出现过城市的逆序数即可满足a.c1>b.c1&&a.c2<b.c2

模板+小点调整=ac:

#include<stdio.h>
#include<string.h>  
#include<math.h>  
  
//#include<map>   
//#include<set>
#include<deque>  
#include<queue>  
#include<stack>  
#include<bitset> 
#include<string>  
#include<iostream>  
#include<algorithm>  
using namespace std;  

#define ll long long  
#define INF 0x3f3f3f3f  
#define mod 1000000007
#define clean(a,b) memset(a,b,sizeof(a))// 水印 
struct node{
	int c1,c2;
//	bool operator < (const node &it) const{
//		if(c2==it.c2)
//			return c1>it.c1;
//		return c2>it.c2;
//	}
}rode[1001000];
ll tree[100100];
int n,m,k;

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

void updata(int i)
{
	while(i<=n)
	{
		tree[i]=tree[i]+1;
		i=i+lowbit(i);
	}
}

int Query(int i)
{
	int res=0;
	while(i>0)
	{
		res=res+tree[i];
		i=i-lowbit(i);
	}
	return res;
}

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

int main()
{
	int t,num=1;
	scanf("%d",&t);
	while(t--)
	{
		clean(tree,0);
		scanf("%d%d%d",&n,&m,&k);
		for(int i=1;i<=k;++i)
			scanf("%d%d",&rode[i].c1,&rode[i].c2);
		//sort(rode+1,rode+1+k);
		sort(rode+1,rode+k+1,cmp);//第二站小的优先,第一站小的优先 
		ll res=0;
		for(int i=1;i<=k;++i)
		{
			//res=res+Query(rode[i].c1-1);
			updata(rode[i].c1);//记录该位置的城市
			res=res+i-Query(rode[i].c1);//求和逆序数的个数
		}
		
		cout<<"Test case "<<num++<<": "<<res<<endl;
	}
	
}

猜你喜欢

转载自blog.csdn.net/qq_40482358/article/details/81209170