今年暑假不AC HDU - 2037 贪心

题解

使用贪心算法 贪心策略按照结束时间排序每次选取 开始时间最晚的一个

AC代码

#include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

const int INF = 0x3f3f3f3f;
const int MAXN = 110;

struct node
{
	int a, b;
	bool operator < (const node &oth) //结束时间升序若相同按照开始时间降序
	{
		if (b != oth.b)
			return b < oth.b;
		return a > oth.a;
	}
}a[MAXN];

int main()
{
#ifdef LOCAL
	freopen("C:/input.txt", "r", stdin);
#endif
	int N;
	while (cin >> N, N)
	{
		for (int i = 0; i < N; i++)
			scanf("%d%d", &a[i].a, &a[i].b);
		sort(a, a + N);
		int ans = 0, last = -1;
		for (int i = 0; i < N; i++)
		{
			if (a[i].a >= last)
				ans++, last = a[i].b;
		}
		cout << ans << endl;
	}

	return 0;
}

猜你喜欢

转载自blog.csdn.net/CaprYang/article/details/85226208