174. Walls
time limit per test: 1.5 sec.
memory limit per test: 32768 KB
memory limit per test: 32768 KB
input: standard
output: 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.
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
0 0 1 0
0 1 0 0
1 0 0 1
2 2 5 7
Output
3
经典的并查集应用,将每个端点看成图的一个点,问加入那条边存在环。不过可能得hash加速 ,我偷懒用了map跑了437ms。
贴上代码:
经典的并查集应用,将每个端点看成图的一个点,问加入那条边存在环。不过可能得hash加速 ,我偷懒用了map跑了437ms。
贴上代码:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<set>
#include<algorithm>
#include<vector>
#include<cstdlib>
#include<map>
#define inf 0xfffffff
#define CLR(a,b) memset((a),(b),sizeof((a)))
#define FOR(a,b) for(int a=1;a<=(b);(a)++)
using namespace std;
int const nMax = 400010;
int const base = 10;
typedef int LL;
typedef pair<LL,LL> pij;
// std::ios::sync_with_stdio(false);
int fa[nMax];
map<pij,int> hash;
int size;
int find(int x) {
return fa[x]==x?fa[x]:fa[x]=find(fa[x]);
}
bool Union(int u,int v) {
int x=find(u),y=find(v);
if(x!=y) {
fa[y]=x;
return true;
}
return false;
}
#define l first
#define r second
int n;
int main(){
pij u,v;
scanf("%d",&n);
hash.clear();size=0;
for(int i=0;i<2*n;i++) fa[i]=i;
int ans=0;
FOR(i,n) {
scanf("%d%d%d%d",&u.l,&u.r,&v.l,&v.r);
if(hash.count(u)==0) {
hash[u]=size++;
}
if(hash.count(v)==0) {
hash[v]=size++;
}
if(!Union(hash[u],hash[v])){
ans=i;
break;
}
}
printf("%d\n",ans);
return 0;
}