想对了一半,还是不扎实
- 原本想将初始化和之后处理一起放到for里面的(i.e. 将push, ans = 1等放到for里面),发现比较麻烦,然后死磕这个,要建函数什么的,看了人家的代码之后发现没有必要,当然是美观了一点。其实能不能将初始化和处理一起写最重要的是看你的思路 is clear or not, sometimes it can unified. But in this case, it need something in the queue, otherwise we need to check every time.
- Know how to compare with struct, it has different flavors, I think the compares below is clear for use.
- Why there is no different when pop the earliest element then push a current element between find the nearest element to modify?
Because the cows are sorted by starting time, which means the cow you currently maintains is the earliest one. And our greedy algorithm is earlier appear earlier to use.
//#define LOCAL
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#define N 50010
using namespace std;
struct interval{
int begin;
int end;
int num;
friend bool operator <(interval a, interval b){
if(a.end == b.end)
return a.begin < b.begin;
return a.end > b.end;
}
}a[N];
bool cmp(interval a, interval b){
if(a.begin == b.begin)
return a.end < b.end;
return a.begin < b.begin;
}
int main(void){
#ifdef LOCAL
freopen("data.in", "r", stdin);
#endif
int n;
int order[N];
priority_queue<interval> q;
scanf("%d", &n);
for(int i = 0; i < n; i++){
scanf("%d%d", &a[i].begin, &a[i].end);
a[i].num = i;
}
sort(a, a + n, cmp);
#ifdef LOCAL
for(int i = 0; i < n; i++)
printf("begin:%d end:%d num:%d\n",
a[i].begin, a[i].end, a[i].num);
#endif
int ans = 1;
q.push(a[0]);
order[a[0].num] = ans;
for(int i = 1; i < n; i++){
interval temp = q.top();
#ifdef LOCAL
printf("begin:%d end:%d num:%d\n",
temp.begin, temp.end, temp.num);
#endif
if(temp.end < a[i].begin){
order[a[i].num] = order[temp.num];
q.pop();
}else{
ans++;
order[a[i].num] = ans;
}
q.push(a[i]);
}
printf("%d\n", ans);
for(int i = 0; i < n; i++)
printf("%d\n", order[i]);
return 0;
}