题解:离散化之后差分数组,注意左闭右闭区间的处理,将点和线段都抽象成点
cpp
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
const int MAXN = 3000000 + 5;
const int INF = -2000000000;
vector<int> g;
int l[MAXN], r[MAXN], d[MAXN];
int get(int val) {
return lower_bound(g.begin(), g.end(), val) - g.begin();
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, x;
cin >> n >> x;
for (int i = 1; i <= n; ++i) {
cin >> l[i] >> r[i];
g.push_back(l[i] * 2);
g.push_back(r[i] * 2 + 1);
}
sort(g.begin(), g.end());
g.erase(unique(g.begin(), g.end()), g.end());
for (int i = 1; i <= n; ++i) {
d[get(l[i] * 2)]++;
d[get(r[i] * 2 + 1)]--;
}
for (int i = 1; i < MAXN; ++i) {
d[i] += d[i - 1];
}
vector<int> res;
int last = INF;
for (int i = 0; i < g.size(); ++i) {
if (d[i] >= x) {
if (last == INF) {
last = (g[i] & 1) != 0 ? (g[i] - 1) / 2 : g[i] / 2;
}
} else {
if (last == INF) continue;
if (g[i] & 1) {
res.push_back(last);
res.push_back((g[i] - 1) / 2);
} else {
res.push_back(last);
res.push_back(g[i] / 2);
}
last = INF;
}
}
cout << res.size() / 2 << '\n';
for (int i = 0; i < res.size(); i += 2) {
cout << res[i] << " " << res[i + 1] << '\n';
}
return 0;
}