papamelon 212. 區間調度問題(挑戰程序設計競賽)

地址 https://www.papamelon.com/problem/212

解答
貪心算法
選擇符合條件中區間結束比較早的那個區間。
可以證明,同樣的選擇區間中,選擇較早結束的區間至少不會得到比選擇較晚結束的區間更差的結果。
基於以上規則,我們將區間按照結束時間排序。
每次選擇起始時間比當前結束時間小的區間,該區間是可以選擇的區間中結束時間最早的。即可

// 1123555.cpp : 此文件包含 "main" 函數。程序執行將在此處開始並結束。
//

#include <iostream>
#include <algorithm>

using namespace std;
/*
5
1 99
2 5
4 7
6 9
8 10
輸出
3
*/

const int N = 100010;
struct Node {
	int l; int r;
}node[N];
int n;

bool cmp(const struct Node& a, const struct Node& b) {
	return a.r < b.r;
}

void solve() {
	sort(node, node + n, cmp);

	int currEnd = -9999999;
	int ans = 0;
	for (int i = 0; i < n; i++) {
		if (currEnd < node[i].l) {
			ans++; currEnd = node[i].r;
		}
	}

	cout << ans << endl;

	return ;
}

int main()
{
	while (cin >> n) {
		for (int i = 0; i < n; i++) {
			int a, b;
			cin >> a >> b;
			if (a > b) { swap(a, b); }
			node[i].l = a; node[i].r = b;
		}

		solve();
	}

	return 0;
}

我的視頻題解空間

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章