贪心算法-求解畜栏问题

题目内容:

有n头牛(1<=n<=50,000)要挤奶。给定每头牛挤奶的时间区间A,B。牛需要呆在畜栏里才能挤奶。一个畜栏同一时间只能容纳一头牛。问至少需要多少个畜栏,才能完成全部挤奶工作,注意:在同一个畜栏的两头牛,它们挤奶时间区间不能在端点重合。

输入格式:

第1行:一个正整数N;
第2…N+1行:第i+1行的两个整数给出第i头奶牛的挤奶时间。

输出格式:

需要畜栏的最小数

输入样例:

5

1 10

2 4

3 6

5 8

4 7

输出样例:

4

#include <iostream>
#include<algorithm>
#include<vector>
using namespace std;
class cow
{
public:
	int l, r, number=0;
	
};
class lcompare
{
public:
	bool operator()(cow a, cow b)
	{
		return a.l < b.l;
	}
};
class rcompare
{
public:
	bool operator()(cow a, cow b)
	{
		return a.r < b.r;
	}
};
int main()
{
	int n, ans = 0;
	lcompare lcompare1;
	rcompare rcompare1;
	vector<cow> v1, v2;
	cin >> n;
	v1.resize(n);
	v2.resize(n);
	for (vector<cow>::iterator it = v1.begin(); it != v1.end(); it++)
		cin >> it->l >> it->r;
	v2 = v1;
	sort(v1.begin(), v1.end(), lcompare1);
	sort(v2.begin(), v2.end(), rcompare1);
	for (vector<cow>::iterator it = v1.begin(); it != v1.end(); it++)
	{
		vector<cow>::iterator a = v2.begin();
		if (!v2.empty() && it->l > a->r)
			a++;
		else 
			ans++;
	}
	cout << ans << endl;
}

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值