sgu174:Walls(并查集判无向图环)

题意:
给出M条线段,保证线段只能端点处相交且不重合,求出最先构成多边形的那条线段。
1<=M<=200000, -1e9<=xi,yi<=1e9
分析:
因为线段只能在端点处相交,而且坐标范围又这么大,我们可以用hash把每个端点保存下来。
对于每条新线段AB,如果点A未出现过,存入hash,否则在hash中找到其点编号,B点类似。
对于一个多边形,我们可以将其视作一个环,只要加上新线段的两点后能构成一个环就可以了。
这里可以用并查集来判环。
如果新加入的两点在同一个分量中,那么与新加进来的线段必定可以与原图构成一个环。
因此判断fa[A]等不等于fa[B]即可。
#include <cstdio>
#include <vector>
using namespace std;
typedef long long LL;
const int MAXM = 200009;
const int mod = 200009;
int m;
int fa[MAXM<<1];
struct cdnt{int x, y, node;};
vector<cdnt> hash[mod];
int ver[MAXM<<1], top;

int deal(int x, int y)
{
	int h, node;
	bool flag = 1;
	h = ((LL)x*2+(LL)y*3)%(LL)mod;
	for(int j = 0, lim = hash[h].size(); j < lim; ++j)
		if(x == hash[h][j].x && y == hash[h][j].y)
		{
			flag = 0;
			node = hash[h][j].node;
			break;	
		}
	if(flag)
	{
		cdnt tmp = {x, y, ++top};
		hash[h].push_back(tmp);	
		node = fa[top] = top;
	}
	return node;
}

int find(int cur)
{
	if(fa[cur] != cur) fa[cur] = find(fa[cur]);
	return fa[cur];
}

int main()
{
	scanf("%d", &m);
	for(int i = 1; i <= m; ++i)
	{
		int x, y, nx, ny;
		scanf("%d%d", &x, &y);
		nx = deal(x, y);
		scanf("%d%d", &x, &y);
		ny = deal(x, y);
		nx = find(nx);
		ny = find(ny);
		if(nx == ny) 
		{
			printf("%d\n", i);
			return 0;	
		}
		fa[nx] = ny;
	}
	printf("0\n");
	return 0;	
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值