hdu2037 this summer without AC [greedy] [interval scheduling problem]

Topics address

hdu2037

Casual working


Code and explanation

This problem using greedy. There are three greedy strategy: the earliest start time, end time of the earliest, with the shortest time. The second is the right strategy, because it is over sooner, behind the more programs you can be seen.
I used to sort the priority queue to the end time value is smaller high priority.
c ++ code is as follows:

#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);
    } 
}

reference

Greedy idea:
step by step, and look one step;
at each step, the election of the current best;
do not look back, do not change the existing selection.
Greedy method only made based on existing information on the current selection, and once made a choice, no matter what the results of the future, this choice will not change. In other words, greed is not the best method to consider a whole, just select it in the sense of local optima made.
Such local optimal choice is not always obtain an overall optimal solution (Optimal Solution), but usually near optimal solution can be obtained (Near-Optimal Solution).

  • Wherein the greedy method to solve the problem:
    1) optimal substructure properties
    when an optimal solution which contains the optimal solution subproblem call this problem the sub-optimal structural properties, also known as the problem of satisfying the optimal principle.
    2) Select the greedy nature of
    the so-called greedy choice is the overall nature of the optimal solution may be the best choice through a series of partially, i.e., to get the greedy choice.
  • Dynamic programming method for solving each sub-problem is usually to a bottom-up manner, while greed rule is usually a top-down manner greedy to make a series of choices.

Guess you like

Origin www.cnblogs.com/hardcoreYutian/p/11455556.html