Segment Tree
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard 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 nn segments [l1,r1],[l2,r2],…,[ln,rn][l1,r1],[l2,r2],…,[ln,rn], li<rili<ri for every ii. 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 nn vertices from these segments. Vertices vv and uu are connected by an edge if and only if segments [lv,rv][lv,rv] and [lu,ru][lu,ru] intersect and neither of it lies fully inside the other one.
For example, pairs ([1,3],[2,4])([1,3],[2,4]) and ([5,10],[3,7])([5,10],[3,7]) will induce the edges but pairs ([1,2],[3,4])([1,2],[3,4]) and ([5,7],[3,10])([5,7],[3,10]) will not.
Determine if the resulting graph is a tree or not.
Input
The first line contains a single integer nn (1≤n≤5⋅1051≤n≤5⋅105) — the number of segments.
The ii-th of the next nn lines contain the description of the ii-th segment — two integers lili and riri (1≤li<ri≤2n1≤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
input
Copy
6 9 12 2 11 1 3 6 10 5 7 4 8
output
Copy
YES
input
Copy
5 1 3 2 4 5 9 6 8 7 10
output
Copy
NO
input
Copy
5 5 8 3 6 2 9 7 10 1 4
output
Copy
NO
Note
The graph corresponding to the first example:
The graph corresponding to the second example:
The graph corresponding to the third example:
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;;
int fa[N];
int fin(int x){
if (x != fa[x]) {
fa[x] = fin(fa[x]);
}
return fa[x];
}
bool unio(int x, int y){
int fx = fin(x), fy = fin(y);
if (fx != fy){
fa[fx] = fy;
return 1;
}
else return 0;
}
vector<pair<int, int>> tree;
set<pair<int, int>> st;
void inpos() {
for (int i = 1; i < N; i++) {
fa[i] = i;
}
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int n; cin >> n;
inpos();
for (int i = 1; i <= n; i++){
int l, r;
cin >> l >> r;
tree.push_back({ l,r });
}
sort(tree.begin(), tree.end());
int cnt = 0;
for (int i = 0; i < n; i++){
int l, r;
l = tree[i].first, r = tree[i].second;
auto _pos = st.upper_bound({ l,0 });
for (auto pos = _pos; pos != st.end(); pos++){
if (pos->first > l && pos->first < r){
cnt++;
if (cnt > n - 1 || unio(i + 1, pos->second + 1) == 0){
cout << "NO\n";
return 0;
}
}
else break;
}
st.insert({ r,i });
}
int root = fin(n);
for (int i = 1; i <= n; i++) {
if (root != fin(i)){
cout << "NO\n";
return 0;
}
}
cout << "YES\n";
return 0;
}