C++矩阵-获取列数,其中最低值与后面列中最高值位于同一行

C++ matrix - Get number of columns where the lowest value is in the same row as the highest value in the columns after it

本文关键字:最高值 于同一 最低值 矩阵 获取 取列数 C++      更新时间:2023-10-16

我正在用C++编写一个程序,其中输入为N(村庄/行的数量)、m(天数/列的数量)和H[N][m]矩阵,其中我单独输入温度(最小-50,最大50)。

输出应该是村庄最低时的总天数温度具有最高的预测温度,然后按升序排列这些天数(列)。

所以如果我输入这样的东西:

3 5 
10 15 12 10 10
11 11 11 11 20
12 16 16 16 20

输出应为:

2 2 3

或输入:

3 3
1 2 3
1 2 3
1 2 3

输出:

2 1 2

我的方法是首先将每天的最低温度和最高预测温度存储到两个单独的阵列中然后写一个for循环,我每天检查每个村庄是否同时包含给定日期的最小值和当天起的最高预测温度。

我有以下代码:

#include <iostream>
const int maxarr = 1000;
int H[maxarr][maxarr];
using namespace std;
void read(int N, int M, int t[maxarr][maxarr]);
void count(int N, int M, int t[maxarr][maxarr]);
int main()
{
int N;
int M;
cout<<"Number of villages? ";
cin>>N;
cout<<"Number of days? ";
cin>>M;
read(N,M,H);
count(N,M,H);
return 0;
}
void read(int N, int M, int t[maxarr][maxarr])
{
for(int i = 0; i < N ; i++)
{
for(int j = 0; j < M ; j++)
{
cin>>t[i][j];
}
}
}
void count(int N, int M, int t[maxarr][maxarr])
{
int mintemparr[maxarr];
int maxtemparr[maxarr];
int mintemp;
int maxtemp;
int days[maxarr];
int cnt = 0;
for(int j = 0; j<M; j++)
{
mintemp = 51;
for(int i = 0; i<N; i++)
{
if(t[i][j]<mintemp)
{
mintemp = t[i][j];
}
mintemparr[j] = mintemp;
}
}
for(int i = 0; i < M-1; i++)
{
maxtemp = -51;
for(int j = 0; j < N; j++)
{
for(int k = i+1; k < M; k++)
{
if(t[j][k]>maxtemp)
{
maxtemp = t[j][k];
}
}
maxtemparr[i] = maxtemp;
}
}
for(int i = 0; i < M-1; i++)
{
for(int j = 0; j < N; j++)
{
for(int k = i+1; k < M; k++)
{
if(t[j][i] == mintemparr[i])
{
if(t[j][k] == maxtemparr[i])
{
days[cnt] = i+1;
cnt++;
//tried an i++ here, didn't work as intended
}
}
else
{
j++;
}
}
}
}
cout<<cnt<<" ";
for(int i = 0; i < cnt; i++)
{
cout<<days[i]<<" ";
}
}

在某些情况下,它可以完美地工作,例如,对于第一个输入,它的输出是应该的第二次输入我得到

6 1 1 1 2 2 2

更长的(1000x1000)输入,我显然不能在这里复制,也会给出错误的结果。我如何才能使此代码按预期工作?

第二个例子之所以得到6 1 1 1 2 2 2,是因为一旦发现某一天是否满足条件,您就不会停下来检查。因此,您发现在第1天,村庄1、村庄2和村庄3(结果中的前三个1)的条件成立,然后第2天也会发生同样的情况。

来自评论

在这里尝试了i++,没有按预期工作

我想您已经发现了这个问题,i++旨在防止当天再次复查。然而,正如你所注意到的,光靠这一点是行不通的——原因是,当你跳到第二天时,你需要确保当天再次从1号村开始检查情况,也需要从一开始就开始寻找最高温度。

要做到这一点,只需添加

++i;   // carry on with the next day
j = 0; // start with the first village in the next iteration
k = i; // search for the highest temperature beginning from day i + 1
// note that at the end of the loop body `k` will be incremented
// so we need to use `k = i` instead of `k = i + 1` as in the loop-initializer here.

cnt++之后代替我上面引用的评论。

通过此更改,可以获得您在问题中描述的两种情况的输出,如您所见。

考虑到您上传到zippyshare的输入,我相信第二个例子的输出应该是3 1 2 3,而不是2 1 2。幸运的是,代码很容易更改以适应这一点:只需将所有k = i + 1替换为k = i,并将新添加的k = i更改为k = i - 1,即可搜索最高预报。