a515簡單矩陣操作的依序組合

CPE:Having Fun with Matrices (UVa 11360)

清楚區分列、欄、數值與轉置操作。

前往題目練習 →回報教學錯誤每筆時間 O(MN²),空間 O(N²)。

解題思路

N小於10,直接以整數矩陣逐條執行即可。row交換兩個橫列,col對每列交換指定兩格;inc與dec分別加1或加9後取模10;transpose把a[r][c]改成舊a[c][r],可用新矩陣,或只交換主對角線上方的成對格。

指令不可重排,因為轉置會改變後續row與col指向的位置。輸入列欄從1開始,交換前轉成0起算。每筆輸出Case #k且沒有冒號,矩陣每列不插空白,最後都再印一個空白行,包含最後一筆。

Step-by-step animation

示意:矩陣12/34,transpose後inc

回報動畫錯誤
步驟 1 / 3

初始

第一列12、第二列34。

1
2
3
4
N
2
已執行
0

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <string>
#include <utility>
using namespace std;
int main() {
    int T;
    cin >> T;
    for (int tc = 1; tc <= T; ++tc) {
        int n;
        cin >> n;
        vector<vector<int>> a(n, vector<int>(n));
        for (auto &row : a) {
            string s;
            cin >> s;
            for (int c = 0; c < n; ++c)
                row[c] = s[c] - '0';
        }
        int m;
        cin >> m;
        while (m--) {
            string op;
            cin >> op;
            if (op == "row" || op == "col") {
                int x, y;
                cin >> x >> y;
                --x;
                --y;
                if (op == "row")
                    swap(a[x], a[y]);
                else
                    for (auto &row : a)
                        swap(row[x], row[y]);
            } else if (op == "transpose") {
                for (int r = 0; r < n; ++r)
                    for (int c = r + 1; c < n; ++c)
                        swap(a[r][c], a[c][r]);
            } else
                for (auto &row : a)
                    for (int &x : row)
                        x = (x + (op == "inc" ? 1 : 9)) % 10;
        }
        cout << "Case #" << tc << '\n';
        for (const auto &row : a) {
            for (int x : row)
                cout << x;
            cout << '\n';
        }
        cout << '\n';
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多