D. Segment Tree

Description:
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⋅1e5) — 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
input
6
9 12
2 11
1 3
6 10
5 7
4 8
output
YES
input
5
1 3
2 4
5 9
6 8
7 10
output
NO
input
5
5 8
3 6
2 9
7 10
1 4
output
NO

Problem solving:

Code:

#include <bits/stdc++.h>
using namespace std;
#define pil    pair<int, int>
#define f      first
#define  s     second
const int     maxn = 1e6 + 10;
int           n, f[maxn];
pil           p[maxn];
map<int, int> pos;
int find(int x)
{
return f[x] != x ? f[x] = find(f[x]) : x;
}
int main()
{
ios::sync_with_stdio(0);
cin >> n;
for (int i = 0; i < n; i++)
cin >> p[i].f >> p[i].s, f[i] = i;
sort(p, p + n);
for (int i = 0; i < n; i++)
{
int mid = p[i].f;
while (true)
{
auto it = pos.upper_bound(mid);
if (it == pos.end() || it->f > p[i].s)
break;
int p = i, q = it->s;
if (find(p) == find(q))
{
cout << "NO\n";
return 0;
}
mid        = it->f;
f[find(p)] = find(q);
}
pos[p[i].s] = i;
}
for (int i = 0; i < n; i++)
{
if (find(i) != find(0))
{
cout << "NO\n";
return 0;
}
}
cout << "YES\n";
return 0;
}