题目描述
输入一个四行五列的矩阵,找出每列最大的两个数。
输入描述:
接下来的四行每行包括五个整数。代表一个四行五列的矩阵,矩阵元素全部是整数。
输出描述:
可能有多组测试数据,对于每组数据,按照样例输出的格式将每列最大的两个数输出,如果最大的两个数中的一个数在这一列中有多个相同的值,则行值取行值小的那一个。
输出时要保留原矩阵的行列顺序,即在原矩阵中行值小的,在输出矩阵中的行值依然小。
示例1
输入
1
1 2 4 9 8
-1 4 9 8 8
12 9 8 7 0
7 8 9 7 0
输出
8 12 9 9 9
8 7 8 9 8
题目解析:难点在于查找最大的两个数,这两个数在原矩阵中有顺序,两个数并不一定是大的在前,小的在后,所以需要保存其位置,最后按位置输出
代码:
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<iostream>
#include<iomanip>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<queue>
using namespace std;
const int INF = 0x3f3f3f3f;
//找最大的两个数,难点在于找到两个最大的数,但是顺序不能变,例如可能最大的在前,二大在后,也可能反过来
int main()
{
int matrix[4][5];
vector<pair<int,int>> vc1,vc2; //记录数字和行下标
for(int i = 0; i < 4; i++){
for(int j = 0; j < 5; j++){
cin >> matrix[i][j];
}
}
//找第一大数字
for(int i = 0; i < 5; i++){
int max = -INF;
int index = -1;
for(int j = 0; j < 4; j++){
if(matrix[j][i] > max){
max = matrix[j][i];
index = j;
}
}
vc1.push_back(make_pair(max,index));
}
//找第二大数字
for(int i = 0; i < 5; i++){
int max = -INF;
int index = -1;
for(int j = 0; j < 4; j++){
if(matrix[j][i] > max && j != vc1[i].second){
max = matrix[j][i];
index = j;
}
}
vc2.push_back(make_pair(max,index));
}
//轮流输出,输出第一行
for(int i = 0; i < 5; i++){
if(vc1[i].second < vc2[i].second){
cout << vc1[i].first << " ";
}else{
cout << vc2[i].first << " ";
}
}
//输出第二行
cout << endl;
for(int i = 0; i < 5; i++){
if(vc1[i].second < vc2[i].second){
cout << vc2[i].first << " ";
}else{
cout << vc1[i].first << " ";
}
}
cout << endl;
vc1.clear();
vc2.clear();
return 0;
}