題目鏈接:https://codeforces.com/contest/1278/problem/D
題目大意:
給定一堆線段[li,ri],每個線段的端點都不一樣,如果兩個線段相交,那麼他們必須是有一段相交而不是內嵌,比如[1,3]與[2,4]相交,而[1,4]與[2,3]不相交。
現在,對於每對相交的線段,我們對他們建邊,比如[l1,r1]與[l2,r2]相交,1和2就可以建邊,問你最後能否建成一顆樹?注意只能是一棵樹,任意兩點之間只有一條唯一的路徑。
思路:
暴力O(n^2)肯定不行,我們需要加速處理。
首先對所有區間對左端點排序,對於當前考慮的區間i,因爲之前的區間左端點一定小於li,所以相交的情況只可能是前面區間的右端點落在[li,ri]這個區間裏面了。而現在是問你能否構成一棵樹,一棵樹最多的邊就是n-1,並且用並查集維護的話,最後所有的點的父親相同。
所以我們可以在set中保存右端點信息,每次來一個新區間[li,ri],我們lower_bound尋找右端點在這個區間內的所有區間,然後暴力地建邊,如果出現建的邊數大於等於n,或者建邊的兩方已經是同一個並查集了,那肯定不行,否則就直接建邊。最後再拍一遍看是否所有點都縮在同一個並查集裏,就ok了。
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e6+10;
set<int>s;
struct Node{
int l,r;
}node[maxn];
int cmp(const Node a,const Node b){
return a.l<b.l;
}
int fa[maxn];
int find_set(int x){
return fa[x]==x?fa[x]:fa[x]=find_set(fa[x]);
}
bool Union(int x,int y){
if(x==y)return true;
int fx=find_set(x),fy=find_set(y);
//printf("Union %d %d\n",fx,fy);
if(fx==fy)return false;
if(fx<fy){
fa[fy]=fx;
}
else{
fa[fx]=fy;
}
return true;
}
map<int,int>mp;
signed main(){
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d%d",&node[i].l,&node[i].r);
fa[i]=i;
}
sort(node+1,node+n+1,cmp);
for(int i=1;i<=n;i++){
mp[node[i].r]=i;
}
int sum=n;
for(int i=1;i<=n;i++){
int l=node[i].l,r=node[i].r;
auto it=s.lower_bound(l);
int cnt=0;
while(it!=s.end()&&*it<r){
//printf("hello %d %d\n",mp[*it],i);
if(!Union(mp[*it],i)){
//printf("hello %d %d\n",mp[*it],i);
puts("NO");
//printf("debug 1\n");
return 0;
}
cnt++;
it++;
}
if(sum-cnt<=0){
puts("NO");
//printf("debug 2\n");
return 0;
}
sum-=cnt;
s.insert(r);
}
for(int i=2;i<=n;i++){
int f=find_set(i);
if(f!=find_set(1)){
puts("NO");
//printf("debug 3\n");
return 0;
}
}
puts("YES");
return 0;
}