C语言算法 活动选择 贪心算法

Problem Description

 sdut 大学生艺术中心每天都有n个活动申请举办,但是为了举办更多的活动,必须要放弃一些活动,求出每天最多能举办多少活动。
Input

 输入包括多组输入,每组输入第一行为申请的活动数n(n<100),从第2行到n+1行,每行两个数,是每个活动的开始时间b,结束时间e;
Output

 输出每天最多能举办的活动数。
Sample Input

12
15 20
15 19
8 18
10 15
4 14
6 12
5 10
2 9
3 8
0 7
3 4
1 3
Sample Output

5

//贪心算法-----活动选择问题
#include<stdio.h>
        
typedef struct act{
    int strat;
    int end;
}Act;

int main(){
    int i,j,k;
    Act temp;
    Act stus[12]={{15,20},{15,19},{8,18},{10,15},{4,14},{6,12},{5,10},{2,9},{3,8},{0,7},{3,4},{1,3}};

    for(i=0;i<12-1;i++){
        k=i;
        for(j=1+i;j<12;j++)
        if(stus[k].end>stus[j].end) k=j;
        if(k!=i){
            temp=stus[k];
            stus[k]=stus[i];
            stus[i]=temp;
        }
    }   

    printf("结束时间由小到大为:");
    for(i=0;i<12;i++)  printf("(%d,%d)  ",stus[i].strat,stus[i].end);
    
    int m,n,post;
    m=0;
    n=1;
    post=1;
    printf("\n第%d的活动时间为:(%d,%d)",post,stus[0].strat,stus[0].end);
    
    while(n<13){
        if(stus[m].end<=stus[n].strat){
        printf("\n第%d的活动时间为:(%d,%d)",post,stus[n].strat,stus[n].end);
        post=post+1;
        m=n;
        n++;
        }
       else n++;
    }
    printf("\n最多能举办%d场活动\n",post);

    return 0;
}

发布了30 篇原创文章 · 获赞 47 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_44040023/article/details/103284523