POJ3190 Stall Reservations 贪心

    这题用贪心法。

    首先对每头牛挤奶的开始时间进行升序排序,然后假设已经使用的stall的集合为S,初始时S为空,每个stall要记录下一个T,表示在T时刻后,该stall变为空闲。

    接着,按顺序对每头奶牛进行查询,在S中选择最小的T的stall,如果T小于该头奶牛的开始挤奶时间,则将此stall分配给该奶牛,同时更新T为该奶牛的结束时间;如果找不到满足条件的stall,就意味着要再申请一个stall了。

#define HEAD
#include <stdio.h>
#include <vector>
#include <math.h>
#include <string.h>
#include <string>
#include <iostream>
#include <queue>
#include <list>
#include <algorithm>
#include <stack>
#include <map>

#include<iostream>  
#include<cstdio>  
using namespace std;

struct STALL
{
	int number;
	int endtime;
	bool operator()(const STALL& a, const STALL& b)
	{
		return a.endtime > b.endtime;
	}
};

struct COW
{
	int start;
	int end;
	int pos;
	int number;
};

bool COWComp(COW& a1, COW& a2)
{
	return a1.start < a2.start;
}

bool COWcomp2(COW& a1, COW& a2)
{
	return a1.number < a2.number;
}

int COSPOS[50001];

int main()
{
#ifdef _DEBUG
	freopen("d:\\in.txt", "r", stdin);
#endif
	memset(COSPOS, 0, sizeof(COSPOS));
	int n;
	scanf("%d\n", &n);
	priority_queue<STALL, vector<STALL>, STALL> pq;
	vector<COW> cows;
	for (int i = 0; i < n;i++)
	{
		COW cow;
		scanf("%d %d\n", &cow.start, &cow.end);
		cow.number = i;
		cows.push_back(cow);
	}
	sort(cows.begin(), cows.end(), COWComp);
	int stallnumber = 0;
	for (int i = 0; i < n;i++)
	{
		if (pq.size() == 0 || pq.top().endtime >= cows[i].start)
		{
			STALL newstall;
			newstall.number = ++stallnumber;
			newstall.endtime = cows[i].end;
			cows[i].pos = stallnumber;
			pq.push(newstall);
		}
		else if (pq.top().endtime < cows[i].start)
		{
			STALL stall = pq.top();
			pq.pop();
			stall.endtime = cows[i].end;
			pq.push(stall);
			cows[i].pos = stall.number;
		}

	}
	printf("%d\n", stallnumber);
	sort(cows.begin(), cows.end(), COWcomp2);
	for (int i = 0; i < n; i++)
	{
		printf("%d\n", cows[i].pos);
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值