传送门:CodeForces-1278D
题目描述
As the name of the task implies, you are asked to do some work with segments and trees.
Recall that a tree is a connected undirected graph such that there is exactly one simple path between every pair of its vertices.
You are given $n$ segments $[l_1,r_1],[l_2,r_2],…,[l_n,r_n]$, $l_i<r_i$ for every $i$. It is guaranteed that all segments’ endpoints are integers, and all endpoints are unique — there is no pair of segments such that they start in the same point, end in the same point or one starts in the same point the other one ends.
Let’s generate a graph with n vertices from these segments. Vertices $v$ and $u$ are connected by an edge if and only if segments $[l_v,r_v]$ and $[l_u,r_u]$ intersect and neither of it lies fully inside the other one.
For example, pairs $([1,3],[2,4])$ and $([5,10],[3,7])$ will induce the edges but pairs $([1,2],[3,4])$ and $([5,7],[3,10])$ will not.
Determine if the resulting graph is a tree or not.
输入描述
The first line contains a single integer $n$ $(1≤n≤5⋅10^5)$ — the number of segments.
The $i$-th of the next n lines contain the description of the $i$-th segment — two integers $l_i$ and $r_i$ $(1≤l_i<r_i≤2*n)$.
It is guaranteed that all segments borders are pairwise distinct.
输出描述
Print “YES” if the resulting graph is a tree and “NO” otherwise.
思路分析
一棵树的概念为只有$n-1$条边,且所有点的父亲都是一个点(并查集维护)
所以枚举需要连边的点,超过$n-1$或者两个已经连通的话肯定不行
暴力枚举肯定不行,可以将线段按照左端点排序,并用set维护之前的右端点,二分查找满足相交的区间就行了
样例输入
6
9 12
2 11
1 3
6 10
5 7
4 8
样例输出
YES
AC代码
#include <functional>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <iomanip>
#include <vector>
#include <string>
#include <cstdio>
#include <queue>
#include <stack>
#include <cmath>
#include <map>
#include <set>
#if __cplusplus >= 201103L
#include <unordered_map>
#include <unordered_set>
#endif
#define ls x<<1
#define rs x<<1|1
#define fi first
#define se second
#define ll long long
#define pb push_back
#define mp make_pair
#define fun function
#define vi vector<int>
#define lowbit(x) x&(-x)
#define pii pair<int,int>
#define all(x) x.begin(),x.end()
#define mem(a,b) memset(a,b,sizeof(a))
#define IOS ios_base::sync_with_stdio(0); cin.tie(0);cout.tie(0);
using namespace std;
const int INF = 0x3f3f3f3f;
const int N=1e6+10;
int f[N];
pair<int,int>a[N];
set<pair<int,int>>s;
int find(int x) {
return f[x]==x?x:f[x]=find(f[x]);
}
bool merge(int x,int y) {
int t1=find(x);
int t2=find(y);
if(t1==t2)return false;
f[t2]=t1;
return true;
}
int main() {
IOS;
#ifdef xiaofan
freopen("1.in","r",stdin);
freopen("1.out","w",stdout);
#endif
int n;
cin>>n;
for(int i=0; i<n; i++) {
cin>>a[i].fi>>a[i].se;
f[i]=i;
}
sort(a,a+n);
int cnt=0;
for(int i=0; i<n; i++) {
for(auto j=s.upper_bound(mp(a[i].fi,0)); j!=s.end(); j++) {
if(a[i].se>j->fi) {
cnt++;
if(cnt>n-1 || !merge(i,j->se)) {
cout<<"NO"<<endl;
return 0;
}
} else {
break;
}
}
s.insert(mp(a[i].se,i));
}
cnt<n-1?cout<<"NO"<<endl:cout<<"YES"<<endl;
return 0;
}