会议安排
这道题很神奇,正解算法:贪心;
首先:贪心 => 排序 => 按最晚结束时间排(升序); 具体原因需要自行体会
然后:按排好的顺序判断当前的会议时间是否能加入;
最后:记录加入的会议个数。
以上的是我一开始的做法,但明显(误)错了…….没有考虑到排在前面的会议和排在后面但花费时间较少的会议交换的情况;
所以正确算法还要加入一个优先队列(降序),把已经判断加入的会议的花费时间放到队列中,每次碰到超过最晚时间但能和队首交换的会议时就把两场会议交换一下(场次不变,花费时间减去两场会议的差值)
#include <bits/stdc++.h>
using namespace std;
struct node{
int c,t;
}m[100010];
int n;
priority_queue<int> q;//优先队列,默认按降序排列
bool cmp(node x,node y){
if(x.t == y.t){
return x.c < y.c;
}
return x.t < y.t;
}
int main(){
scanf("%d", &n);
for(int i = 1; i <= n; i++){
scanf("%d %d", &m[i].t, &m[i].c);
}
sort(m+1, m+n+1, cmp);
int time = 0, ans = 0;
for(int i = 1; i <= n; i++){
if(time + m[i].c <= m[i].t){
q.push(m[i].c);
time += m[i].c;
ans++;
}
else if(!q.empty() && m[i].c < q.top()){
if(time - q.top() + m[i].c <= m[i].t){
time -= q.top();
time += m[i].c;
q.pop();
q.push(m[i].c);
}
}
}
cout<< ans <<endl;
return 0;
}