sgu 174 Walls 并查集+hash

People of country T-land lived on the big plain many years ago. It is happened so that they started to quarrel, so they began to build walls to separate from each other. 
One day they realized that walls surround some part of the country. Your task is to determine which wall was build first to surround a part of the T-land.

Input
The first line of input contains one number M (1<=M<=200000) - number of walls. Each of the following M lines contains four integer numbers: Cartesian coordinates of two ends of each wall. Walls are rectilinear segments with positive length, two walls can cross only by ends, and walls can't coincide. All coordinates do not exceed 10^9 by its absolute values.

Output
Write the answer in the single line of output. If all the walls leave the territory opened, write 0.

Sample test(s)

Input
 
4  
0 0 1 0  
0 1 0 0  
1 0 0 1  
2 2 5 7
Output
 
3

题意:在平面上依次给出一些线段,这些线段只可能在端点重合或分开,当添加某一条线段后,这条线段能和已添加的线段围成一个封闭图形,输出这条线段的下标。

思路:每添加一条线段就合并两个端点,当添加某条线段发现两端都在同一个集合中时,就是答案。但是并查集并不能直接将点串起来,所以先要用hash给点一次编号,然后再用并查集。

代码:

#include <cstdio>
#include <map>
using namespace std;
#define maxn 200000*2+10

struct Point{
	int x,y;
	Point (){}
	Point (int a,int b):x(a),y(b){}
	bool friend operator <(Point a,Point b){
		if(a.x==b.x) return a.y<b.y;
		return a.x < b.x;
	}
};
map<Point,int> mp;
int n;
int cnt;
int fa[maxn];

void init(){
	for(int i=1;i<maxn;i++) fa[i] = i;
}

int findRoot(int x){
	if(x==fa[x]) return x;
	return findRoot(fa[x]);
}

int main(){
	scanf("%d",&n);
	int a1,b1,a2,b2;
	cnt = 1;
	int ans = 0;
	int temp = 1;
	init();
	while(n--){
		scanf("%d %d %d %d",&a1,&b1,&a2,&b2);
		Point p1(a1,b1),p2(a2,b2);
		int x1,x2;
		if(mp[p1]==0) x1 = mp[p1] = cnt++;
		else x1 = mp[p1];
		
		if(mp[p2]==0) x2 = mp[p2] = cnt++;
		else x2 = mp[p2];
		
		x1 = findRoot(x1), x2 = findRoot(x2);
		if(x1==x2) if(ans==0) ans = temp;
		fa[x1] = x2;
		
		temp++;
	}
	printf("%d\n",ans);
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值