PAT 乙级 1092 最好吃的月饼 (20分)---【结构体/数组 求和 找最值】

8 篇文章 0 订阅
6 篇文章 0 订阅


在这里插入图片描述
输入格式:
输入首先给出两个正整数 N(≤1000)和 M(≤100),分别为月饼的种类数(于是默认月饼种类从 1 到 N 编号)和参与统计的城市数量。

接下来 M 行,每行给出 N 个非负整数(均不超过 1 百万),其中第 i 个整数为第 i 种月饼的销量(块)。数字间以空格分隔。

输出格式:
在第一行中输出最大销量,第二行输出销量最大的月饼的种类编号。如果冠军不唯一,则按编号递增顺序输出并列冠军。数字间以 1 个空格分隔,行首尾不得有多余空格。

输入样例:

5 3
1001 992 0 233 6
8 0 2018 0 2008
36 18 0 1024 4

输出样例:

2018
3 5

思路1:

采用结构体:
1.设置变量,开辟二维数组,存放值
2.设置求和变量,开辟一维数组,存和
3.遍历,求最大值,找到下标,并先输出。
4.再遍历,找与之一样大小的数的下标,输出,注意空格

改进前:

#include<bits/stdc++.h>
using namespace std;

struct Moon {
	int total;
	int s;
};

int main(){
	int n;//月饼种类 
	int m;//参与城市 
	scanf("%d%d",&n,&m);
	Moon moon[m][n]={}; 
	Moon sum[n]={};	

	for(int i = 0; i < m; i++){
		for(int j = 0; j < n; j++){
			cin>>moon[i][j].total;
		}
	}
	for(int i = 0; i < n; i++){
		for(int j = 0; j < m; j++){
			sum[i].s+=moon[j][i].total;
		}
	}

	int Max=0;
	for(int i = 0; i < n; i++){
		if(sum[i].s>sum[Max].s){
			Max=i;
		}
	}

	cout<<sum[Max].s<<endl;
    cout<<Max+1;
	for(int i = 0; i < n; i++){
		if(i==Max) continue;
		if(sum[i].s==sum[Max].s){
			cout<<" "<<i+1;
		}
	}	
	return 0;
} 

思路2:

采用数组:不使用结构体

改进后:

#include<bits/stdc++.h>
using namespace std;

struct Moon {
	int total;
	int s;
};

int main(){
	int n;//月饼种类 
	int m;//参与城市 
	scanf("%d%d",&n,&m);
	Moon moon[m][n]={}; 
	Moon sum[n]={};	
	int Max=0;
	int d;
//	int sum[n]={};
	for(int i = 0; i < m; i++){
		for(int j = 0; j < n; j++){
			cin>>moon[i][j].total;
			sum[j].s+=moon[i][j].total;
//			cin>>d;
//			sum[j]+=d;
			if(i==m-1){
				Max=max(Max,sum[j].s);
			}
		}
	}
//	for(int i = 0; i < n; i++){
//		for(int j = 0; j < m; j++){
//			sum[i].s+=moon[j][i].total;
//		}
//	}

//	for(int i = 0; i < n; i++){
//		Max=max(Max,sum[i].s);
//	}

	cout<<Max<<endl;
	int c=0;
	for(int i = 0; i < n; i++){
		if(sum[i].s==Max){
			if(c) cout<<" ";
			cout<<i+1;
			c++;
		}
	
	}
	
	return 0;
} 

最后形式:

#include<bits/stdc++.h>
using namespace std;

int main(){
	int n;//月饼种类 
	int m;//参与城市 
	scanf("%d%d",&n,&m);

	int Max=0;
	int d;
	int sum[n]={};
	for(int i = 0; i < m; i++){
		for(int j = 0; j < n; j++){
		
			cin>>d;
			sum[j]+=d;
			if(i==m-1){
				Max=max(Max,sum[j]);
			}
		}
	}


	cout<<Max<<endl;
	int c=0;
	for(int i = 0; i < n; i++){
		if(sum[i]==Max){
			if(c) cout<<" ";
			cout<<i+1;
			c++;
		}
	
	}
	
	return 0;
} 

注意!!!

一维数组要初始化!!!Moon sum[n]={};
要不然一直是10分!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值