sgu 174 Walls (并查集)

174. Walls
time limit per test: 1.5 sec.
memory limit per test: 32768 KB
input: standard
output: standard



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


题意:给定n道墙,保证只有端点相交,问第几道墙最先与原来的墙围成一个封闭区间

题解:用并查集,将墙的2个坐标点看成2个点,每次判断给定的2个点是否在同一个集合,在的话就说明并查集中有环,则形成封闭区间,否则将2个点并入同一个集合。另外,找某一个点之前是否出现过的时候可用map<point,int> 作映射,其中point是每个点的结构体


#include<stdio.h>
#include<string.h>
#include<map>
using namespace std;
struct point{
    int x,y;
};
struct seg{
    point a,b;
}c[400005];
map <point,int > has;
bool operator < (const point &x,const point &y) 
{
    if(x.x!=y.x) return x.x<y.x;
    return x.y<y.y;
}
int n,v[400005];
int fin(int x)  //路径压缩并查集
{
    if(x==v[x]) return x;
    return v[x]=fin(v[x]);
}
int bingchaji()
{
    for(int i=0;i<=2*n;i++) v[i]=i;
    int cou=1,res=0;
    for(int i=1,x,y;i<=n;i++)
    {
        if(has.count(c[i].a)) x=has[c[i].a];  //出现过的话直接通过map映射找出下标
        else x=has[c[i].a]=cou++;  //没出现过就给一个新的点
        if(has.count(c[i].b)) y=has[c[i].b];
        else y=has[c[i].b]=cou++;
        x=fin(x),y=fin(y);
        if(x==y)
        {
            res=i;
            break;
        }
        v[x]=y;
    }
    return res;
}
int main()
{
    while(scanf("%d",&n)>0)
    {
        for(int i=1;i<=n;i++)
            scanf("%d%d%d%d",&c[i].a.x,&c[i].a.y,&c[i].b.x,&c[i].b.y);
        int res=bingchaji();
        printf("%d\n",res);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值