矩阵列比较

时间:2019-05-22 08:43:30

标签: c++ algorithm matrix

我必须比较矩阵列。

我尝试了许多变体,但据我所知,是当我比较“彼此相邻”的列时。

// N rows
// M columns

#include <iostream>

using namespace std;

int main()
{
    ios_base::sync_with_stdio(false);

    int N, M, ok = 1;
    const int maxn = 1000;
    const int maxm = 1000;
    short H[maxn][maxm];

    cin >> N >> M;

    for (int i=0; i<N; i++){
        for (int j=0; j<M; j++){
            cin >> H[i][j];
        }
    }

    for (int j = 1; j < M; ++j)
    {
        ok = 1;
        for (int i = 0; i < N; ++i)
        {
            if (H[i][j-1] >= H[i][j])
            {
                ok = 0;
            }
        }
        if (ok)
        {
            cout << j+1 << endl;
            return 0;
        }
    }
    cout << -1 << endl;
    return 0;
}

我必须返回第一列的索引为true,即该列的每个元素都大于任何其他列的元素。 (未汇总。)

例如:

10 10 12 15 10
11 11 11 13 20
12 16 16 16 20

它返回4,因为第4列的每个元素都大于第1列的元素。 如果没有,则必须返回-1

1 个答案:

答案 0 :(得分:0)

您需要另一个内部循环来遍历所有其他列:

#include <ios>
#include <iostream>

int main()
{
    using namespace std;
    ios_base::sync_with_stdio(false);

    int N, M, ok = 1;
    const int maxn = 1000;
    const int maxm = 1000;
    short H[maxn][maxm];

    cin >> N >> M;

    for (int i=0; i<N; i++){
        for (int j=0; j<M; j++){
            cin >> H[i][j];
        }
    }

    for (int j = 0; j < M; ++j)
    {
        for (int j2 = 0; j2 < M; ++j2)
        {
            if (j == j2) continue;
            ok = 1;
            for (int i = 0; i < N; ++i)
            {
                if (H[i][j] <= H[i][j2])
                {
                    ok = 0;
                    break;
                }
            }
            if (ok)
            {
                cout << j + 1 << endl;
                return 0;
            }
        }
    }
    cout << -1 << endl;
    return 0;
}

输入:

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

此打印:

4

See it on Rextester

相关问题