-
Notifications
You must be signed in to change notification settings - Fork 0
/
F.cpp
84 lines (69 loc) · 1.43 KB
/
F.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
void solve()
{
int n;
cin >> n;
vector<array<ll, 3>> a(n);
for (int i = 0; i < n; i++) {
ll l, r;
cin >> l >> r;
a[i] = {l, r, i};
}
sort(a.begin(), a.end(), [&](array<ll, 3> x, array<ll, 3> y) {
if (x[1] == y[1]) return x[0] < y[0];
return x[1] <= y[1];
});
vector<ll> nonOverlap(n, 0);
// get ranges that ends before and doesn't overlap
for (int i = 0; i < n; i++) {
ll l = 0, r = i - 1, mergeIndex = i;
while (l <= r) {
ll mid = l + (r - l) / 2;
if (a[mid][1] >= a[i][0]) {
mergeIndex = mid;
r = mid - 1;
}
else {
l = mid + 1;
}
}
nonOverlap[a[i][2]] += (mergeIndex);
}
sort(a.begin(), a.end());
// get ranges that ends after and doesn't overlap
for (int i = 0; i < n; i++) {
ll l = i + 1, r = n - 1, mergeIndex = i;
while (l <= r) {
ll mid = l + (r - l) / 2;
if (a[mid][0] <= a[i][1]) {
mergeIndex = mid;
l = mid + 1;
}
else {
r = mid - 1;
}
}
nonOverlap[a[i][2]] += (n - 1 - mergeIndex);
}
ll ans = n + 10;
for (int i = 0; i < n; i++) {
ans = min(ans, nonOverlap[i]);
}
cout << ans << '\n';
}
int main()
{
#ifndef ONLINE_JUDGE
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
//freopen("Error.txt", "w", stderr);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL), cout.tie(NULL);
int t = 1;
cin >> t;
while (t--) solve();
return 0;
}