學校禮堂每天都有許多活動申請使用,但這些活動的時間經常發生衝突。小劉的任務是安排這些活動,使得在同一時間段內最多只能舉行一場活動,並且要盡可能安排更多的活動。這是一個經典的區間調度問題,可以用貪心算法高效求解。
給定 n 個活動,每個活動有起始時間 Bᵢ 和結束時間 Eᵢ (Bᵢ ≤ Eᵢ)。若上一個活動在時間 t 結束,下一個活動最早需在 t+1 才能開始。目標是選出最多數量的不重疊活動。
核心思想:優先選擇結束時間最早的活動。這樣能為後續活動留出更多可用時間,從而最大化總活動數。
#include <bits/stdc++.h>
using namespace std;
struct Activity {
int start, end;
};
bool cmp(const Activity &a, const Activity &b) {
return a.end < b.end;
}
int main() {
int m; scanf("%d", &m);
while (m--) {
int n; scanf("%d", &n);
vector<Activity> acts(n);
for (int i = 0; i < n; ++i)
scanf("%d %d", &acts[i].start, &acts[i].end);
sort(acts.begin(), acts.end(), cmp);
int cnt = 1, last_end = acts[0].end;
for (int i = 1; i < n; ++i) {
if (acts[i].start >= last_end + 1) {
++cnt;
last_end = acts[i].end;
}
}
printf("%d\n", cnt);
}
return 0;
}
此問題是貪心算法在區間調度中的典型應用,同樣適用於會議室分配、任務調度等實際場景。