貪心(入門簡單題)

Ostrichcrab發表於2018-06-02

有若干個活動,第i個開始時間和結束時間是[Si,fi),只有一個教室,活動之間不能交疊,求最多安排多少個活動?

Input
第一行一個正整數n (n <= 10000)代表活動的個數。
第二行到第(n + 1)行包含n個開始時間和結束時間。
開始時間嚴格小於結束時間,並且時間都是非負整數,小於1000000000
Output
一行包含一個整數表示活動個數。
Input示例
3
1 2
3 4
2 9
Output示例
2
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e4+5;
struct node
{
	int s,e;
} a[maxn];
bool  cmp(node x,node y)
{
	if(x.e<y.e) return true;
	else if(x.e==y.e&&x.s>y.s) return true;
	return false;
}
int main()
{
	int n,i,j,ans,end;
	cin>>n;
	for(i = 0;i<n;i++)
		cin>>a[i].s>>a[i].e;
	sort(a,a+n,cmp);
	ans = 0;
	end = -1e9-100;
	for(i =0;i<n;i++)
	{
		if(a[i].s>=end)
		{
			ans++;
			end=a[i].e;
		}
	}
	cout<<ans<<endl;
	return 0;
}
/*
3
1 2
3 4
2 9
*/ 


相關文章