AcWing 803. 区间合并
原题链接
简单
作者:
李哥
,
2020-04-09 18:36:06
,
所有人可见
,
阅读 616
思想:维护一个区间
JAVA
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
static List<Seg> segs = new ArrayList<Seg>();
static class Seg{
int l, r;
public Seg(int l, int r) {
this.l = l; this.r = r;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for (int i = 0; i < n; i++) {
segs.add(new Seg(in.nextInt(), in.nextInt()));
}
segs.sort((a, b) -> Integer.compare(a.l, b.l)); // 按区间左端升序
int L = segs.get(0).l, R = segs.get(0).r;
int res = 1;
for (Seg seg : segs) {
if (seg.l <= R) R = Math.max(R, seg.r);
else {
res ++;
L = seg.l; R = seg.r;
}
}
System.out.println(res);
}
}
C++
#include <iostream>
#include <algorithm>
using namespace std;
typedef pair<int, int> PII;
const int N = 100010;
int n;
PII segs[N];
int main()
{
cin >> n;
for (int i = 0; i < n; i ++ ) cin >> segs[i].first >> segs[i].second;
sort(segs, segs + n);
int start = segs[0].first, end = segs[0].second; // 维护 [start, end]
int res = 1;
for (auto seg : segs)
{
int l = seg.first, r = seg.second;
if (r <= end) continue; // 覆盖 不需要更新
if (l <= end && r > end) end = r; // 有交集 修改end
else // 无交集 更新
{
res ++;
start = l, end = r;
}
}
cout << res << endl;
return 0;
}