D. Segment Tree
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
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 [l1,r1],[l2,r2],…,[ln,rn], li<ri 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 [lv,rv] and [lu,ru] 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.
Input
The first line contains a single integer n (1≤n≤5⋅105) — the number of segments.
The i-th of the next n lines contain the description of the i-th segment — two integers li and ri (1≤li<ri≤2n).
It is guaranteed that all segments borders are pairwise distinct.
Output
Print “YES” if the resulting graph is a tree and “NO” otherwise.
Examples
inputCopy
6
9 12
2 11
1 3
6 10
5 7
4 8
outputCopy
YES
inputCopy
5
1 3
2 4
5 9
6 8
7 10
outputCopy
NO
inputCopy
5
5 8
3 6
2 9
7 10
1 4
outputCopy
NO
这道题思路挺简单的,应该一看到题目就能想到。先排个序就好了。
然后我们可以set或者BIT维护一下,然后建图就好了。
set更简单,,但是我写的BIT。BIT上面暴力二分。
AC代码:
#pragma GCC optimize(2)
#include<bits/stdc++.h>
//#define int long long
#define lowbit(x) (x&(-x))
using namespace std;
const int N=5e5+10;
int n,m,tot,d[N<<1],pos[N<<1],mx,f[N],flag;
struct node{int l,r;}t[N]; set<int> g[N];
int cmp(node a,node b){return a.l<b.l;}
inline void add(int x){for(;x<=m;x+=lowbit(x)) d[x]+=1;}
inline int ask(int x){int s=0; for(;x;x-=lowbit(x)) s+=d[x]; return s;}
inline int sum(int l,int r){return ask(r)-ask(l-1);}
int find(int x){return x==f[x]?x:f[x]=find(f[x]);}
signed main(){
cin>>n; m=n<<1;
for(int i=1;i<=n;i++) scanf("%d %d",&t[i].l,&t[i].r),f[i]=i;
sort(t+1,t+1+n,cmp);
for(int i=1;i<=n;i++){
tot+=sum(t[i].l,t[i].r); if(tot>=n) return puts("NO"),0;
int L=t[i].l,R=t[i].r;
while(sum(L,R)&&L<=R){
int cl=L,cr=R;
while(cl<cr){
int mid=cl+cr>>1;
if(sum(cl,mid)) cr=mid;
else cl=mid+1;
}
L=cl+1; int x=find(i),y=find(pos[cl]);
if(x==y) return puts("NO"),0;
else f[x]=y;
}
add(t[i].r); pos[t[i].r]=i;
}
for(int i=2;i<=n;i++) if(find(i)!=find(1)) flag++;
puts((!flag&&tot==n-1)?"YES":"NO");
return 0;
}