这题用贪心法。
首先对每头牛挤奶的开始时间进行升序排序,然后假设已经使用的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;
}