hdu2037node
本题使用贪心。有三种贪心策略:开始时间最先,结束时间最先,用时最短。第二种是正确的策略,由于结束得越早,后面就能够有越多节目被看。
我使用了优先队列进行排序,以结束时间数值小的为高优先级。
c++代码以下:ios
#include<iostream> #include<queue> using namespace std; struct node{ int Beg; int End; friend bool operator<(node n1,node n2){ return n1.End>n2.End;//End小的优先级高 } }TV; int main() { int n;//节目总数 int count;//最多能够看完的节目总数 int last_end; while(~scanf("%d",&n)&&n){ priority_queue<node>chn; while(n--){ scanf("%d%d",&TV.Beg,&TV.End); chn.push(TV); } count=1;//能够看完第一个节目 last_end=chn.top().End;//第一个看完的节目的结束时间 /*while(!chn.empty()){ printf("%d %d\n",chn.top().Beg,chn.top().End); chn.pop(); }*/ while(1){ if(chn.empty()) break; if(chn.top().Beg>=last_end){//能够看这个节目 count++; last_end=chn.top().End; chn.pop(); } else{//不能看这个节目 chn.pop(); } } printf("%d\n",count); } }
贪心法思想:
走一步看一步,并且只看一步;
在每一步,选当前最优的;
不回头,不改变已有的选择。
贪心法只根据当前已有的信息作出选择,并且一旦作出了选择,无论未来有什么结果,这个选择都不会改变。换言之,贪心法并非从总体最优考虑,它所作出的选择只是在某种意义上的局部最优。
这种局部最优选择并不总能得到总体最优解(Optimal Solution),但一般能得到近似最优解(Near-Optimal Solution)。c++