UVA-1153 Keep the Customer Satisfied (贪心)
题目大意:有n件工作,做每件工作的消耗时间为s,截止时间为d,问最多能做完几件工作。
题目分析:贪心策略:优先做截止时间靠前的,一旦做不完当前工作,则从已经做过的工作中删去一件耗时最长的,用当前工作取代之。
代码如下:
# include<iostream>
# include<cstdio>
# include<vector>
# include<queue>
# include<cstring>
# include<algorithm>
using namespace std;
struct Work
{
int s,t;
Work(int _s,int _t):s(_s),t(_t){}
bool operator < (const Work &a) const {
return s<a.s;
}
};
vector<Work>w;
priority_queue<Work>q;
bool myComp(const Work &a,const Work &b)
{
return a.t<b.t;
}
int solve(int n)
{
while(!q.empty()) q.pop();
int ans=0,t=0;
for(int i=0;i<n;++i){
t+=w[i].s;
++ans;
q.push(w[i]);
if(t>w[i].t){
Work u=q.top();
q.pop();
t-=u.s;
--ans;
}
}
return ans;
}
int main()
{
int T,s,t,n;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
w.clear();
for(int i=0;i<n;++i){
scanf("%d%d",&s,&t);
w.push_back(Work(s,t));
}
sort(w.begin(),w.end(),myComp);
printf("%d\n",solve(n));
if(T)
printf("\n");
}
return 0;
}


浙公网安备 33010602011771号