首页 > 代码库 > 贪心算法入门典型案例

贪心算法入门典型案例

在N行M列的正整数矩阵中,要求从每行中选出1个数,
使得选出的总共N个数的和最大。
输入:
第一行两个正整数N和M,用空格隔开,表示行数和列数
第2行到第N+1行,每行M个用空格隔开的整数 ,表示矩阵
输出
最大总和

 1 #include <stdio.h>
 2 #include<stdlib.h>
 3 #include<time.h>
 4 
 5 int main()
 6 {
 7     int i,j,N,M;
 8     int total=0;
 9     int maxI,t;
10     
11     //srand((unsigned int)time(0));
12     scanf("%d%d",&N,&M);
13     for(i=0;i<N;i++)
14     {
15         scanf("%d",&maxI);
16         //maxI=rand()%991+10;
17         //printf("%3d ",maxI);
18         
19         for(j=1;j<M;j++)
20         {
21             scanf("%d",&t);
22             //t=rand()%991+10;
23             //printf("%3d ",t);
24             
25             if(t>maxI) maxI=t;
26         }
27         
28         //printf("----%d\n",maxI);
29         
30         total=total+maxI;
31     }
32     printf("%d\n",total);
33     return 0;
34 }

 

贪心算法入门典型案例