[HDU] [2037] No AC This Summer

Problem Description

Loading...

Problem Analysis

Greedy algorithm
(Although I still don’t quite understand what a greedy algorithm is)

The difficulty is sorting by program end time
You need to work it out yourself

When I first wrote it, I hadn’t learned structs yet
so I wrote it with arrays, which was longer

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include<stdio.h>
int main() {
    int n,i,j,k,t;
    while(scanf("%d",&n),n!=0) {
        int re=1,result=1;
        int Ti_s[100],Ti_e[100];
        Ti_s[0]=Ti_e[0]=0;
        for(i=0; i<n; i++) {
            scanf("%d %d",&Ti_s[i],&Ti_e[i]);
            for(k=0; k<i; k++) {
                if(Ti_e[i]<Ti_e[k]) {
                    t=Ti_e[k];
                    Ti_e[k]=Ti_e[i];
                    Ti_e[i]=t;
                    t=Ti_s[k];
                    Ti_s[k]=Ti_s[i];
                    Ti_s[i]=t;
                }
            }

        }
//      for(i=0; i<n; i++) {
//          for(k=i+1,j=i; k<n; k++) {
//              if(Ti_e[j]<=Ti_s[k]) {
//                  j=k;
//                  re++;
//              }
//          }
//          if(re>result)
//              result=re;
//          if(i==0)
//              result=re;
//          re=1;
//      }
            for(k=1,j=0; k<n; k++) {
                if(Ti_e[j]<=Ti_s[k]) {
                    j=k;
                    re++;
                }
            }
        printf("%d\n",re);
    }
    return 0;
}

The one below uses structs
but it also doesn’t use sort

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include<stdio.h>
struct tv {
    int Ti_s;
    int Ti_e;
};
int main() {
    int i,k;
    int n,result;
    while(scanf("%d",&n),n!=0) {
        result=1;
        struct tv b[n],t;
        b[0].Ti_s=b[0].Ti_e=0;
        for(i=1; i<=n; i++)
            scanf("%d %d",&b[i].Ti_s,&b[i].Ti_e);
        for(i=1; i<=n; i++) {
            for(k=1; k<=n-i+1; k++) {
                if(b[k].Ti_e<b[k-1].Ti_e) {
                    t=b[k];
                    b[k]=b[k-1];
                    b[k-1]=t;
                }
            }
        }
        for(i=2,t=b[1]; i<=n; i++) {
            if(b[i].Ti_s>=t.Ti_e) {
                result++;
                t=b[i];
            }
        }
        printf("%d\n",result);
    }
    return 0;
}

A problem worth doing

Also attaching an excellent explanatory blog post:
HDU2037 No AC This Summer Greedy Algorithm

Loading...