c++ - C ++矩阵 - 获取最低值与其后列中的最高值在同一行中的列数
问题描述
我正在用 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
s替换为k = i
并更改新添加的 s,k = i
以便k = i - 1
搜索最高预测包括今天。
推荐阅读
- mysql - Websphere Liberty 18.0.0.3 MySQL 数据源对象未注入
- php - php 的回复说我的电子邮件字段是空的:Ionic
- blockchain - Sawtooth – 按地址查询交易
- sql - 当查询返回 NULL 时,SQL COALESCE 和 IS NULL 不返回空格
- date - 在 Kotlin 中初始化日期
- java - 在 Koltin/Java 中,如何强制使用来自 Maven 依赖项的同名类覆盖本地项目类?
- php - 如何从同一服务器上的另一个域调用 php 文件
- java - 如果 value 是实例,则 TreeMap 按值排序
- c# - SquareUp 请求令牌:禁止
- java - 如何将 JSON 转换为 POJO 类?