堆 + 贪心
难得的好题,自己确实没想到,看了下别人的想法。.
http://www.acjoke.com/?p=164 这个链接的证明比较给力
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<queue>
#include<stack>
#include<algorithm>
using namespace std;
const int maxn = 50050;
struct Line
{
int l,r,index;
Line(const int& l = 0,const int& r = 0,const int&index = 0):l(l),r(r),index(index){}
Line(const Line& rsh)
{
l = rsh.l;
r = rsh.r;
index = rsh.index;
}
bool operator < (const Line& rsh) const
{
return l < rsh.l;
}
};
struct Heap
{
int id;
int fin;
Heap(const int& id = 0 ,const int& fin = 0):id(id),fin(fin){}
Heap(const Heap& rsh)
{
id = rsh.id;
fin = rsh.fin;
}
bool operator < (const Heap& rsh) const
{
return fin > rsh.fin;
}
};
int result[maxn];
vector<Line> lines;
priority_queue<Heap> heaps;
void put_cow( int i,bool flag)
{
Heap heap;
if(flag)
{
heap.id = heaps.size() + 1;
}
else
{
heap.id = heaps.top().id;
heaps.pop();
}
heap.fin = lines[i].r;
result[lines[i].index] = heap.id;
heaps.push(heap);
}
int main()
{
#ifdef LOCAL
freopen("in.txt","r",stdin);
#endif // LOCAL
int n;
scanf("%d",&n);
int l,r;
for(int i = 0 ; i < n ; i ++)
{
scanf("%d %d",&l,&r);
lines.push_back(Line(l,r,i));
}
sort(lines.begin(),lines.end());
put_cow(0,true);
for(int i = 1 ; i < n ; i++)
{
put_cow(i,lines[i].l <= heaps.top().fin);
}
printf("%d\n",heaps.size());
for(int i = 0 ; i < n ; i++)
{
printf("%d\n",result[i]);
}
return 0;
}