a684中等區間覆蓋的最遠延伸貪心
CPE:Minimal coverage (UVa 10020)
每次從能接上已覆蓋區域的線段中,挑右端最遠者。
解題思路
將所有線段依左端點排序,維護已連續覆蓋 [0,end]。下一條線段必須滿足 L≤end,否則會留下缺口。在所有符合條件的候選中選 R 最大者,因為它用同樣一條線段能覆蓋最遠;任何最優解的下一條都可被它替換而不增加後續需求。
掃描指標持續向右,檢查所有 L≤end 的線段,選出的線段必須使 R>end 才有進展。若沒有則輸出 0;若 end≥M,輸出選段數與依 L 排序的端點。每筆的 0 0 是線段結束符,輸入空白行可忽略,輸出案例間空一行。本地固定比對只採最優集合唯一的測資;一般原題多解可任選。
Step-by-step animation
示意:M=7,線段 [-1,3]、[0,2]、[2,5]、[4,7]
步驟 1 / 3
起點 0
可用前兩段,選右端 3 者。
[-1,3]
[0,2]
[2,5]
[4,7]
- end
- 3
- 條數
- 1
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int tests;
cin >> tests;
for (int tc = 0; tc < tests; tc++) {
int target, l, r;
cin >> target;
vector<pair<int, int>> a, chosen;
while (cin >> l >> r && (l || r))
a.push_back({l, r});
sort(a.begin(), a.end());
int end = 0, i = 0;
while (end < target) {
int far = end;
pair<int, int> best;
while (i < (int)a.size() && a[i].first <= end) {
if (a[i].second > far) {
far = a[i].second;
best = a[i];
}
i++;
}
if (far == end)
break;
chosen.push_back(best);
end = far;
}
if (tc)
cout << '\n';
if (end < target)
cout << "0\n";
else {
sort(chosen.begin(), chosen.end());
cout << chosen.size() << '\n';
for (auto [x, y] : chosen)
cout << x << ' ' << y << '\n';
}
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。