原题 AtCoder-abc214_e
题意
有 次询问,每次给定 个区间 ,求这 个区间是否满足每个区间中取一个数 个区间取的数不相同,如果可以输出 Yes,否则输出 No。
算法
排序 + 贪心 先按左端点 排序, 表示区间左端点可以放到最左边的限制, 表示每次找到所有区间中右端点最小的放在 。如果 ,则不能,输出 No,否则 ++ (取出了队头这个元素)并且弹出队头。由于需要求出最小值,所以可以用优先队列来维护这个过程。
时空复杂度
时间复杂度
。
空间复杂度
。
代码
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 2e5 + 5;
struct Node {
int l, r;
} a[N];
int t, n, s, x;
void solve() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i].l >> a[i].r;
}
sort(a + 1, a + n + 1, [](const Node &i, const Node &j) {return i.l < j.l;});
s = x = 0;
priority_queue<int, vector<int>, greater<int>> q;
while (x < n) {
if (q.empty()) {
q.push(a[++x].r);
s = a[x].l;
}
while (x < n && a[x + 1].l <= s) {
q.push(a[++x].r);
}
if (q.top() < s++) {
cout << "No\n";
return ;
}
q.pop();
}
while (!q.empty()) {
if (q.top() < s++) {
cout << "No\n";
return ;
}
q.pop();
}
cout << "Yes\n";
}
int main() {
ios::sync_with_stdio(0), cin.tie(0);
cin >> t;
while (t--) {
solve();
}
return 0;
}