a186簡單二維陣列、座標與鄰居

TOI 2020/06 新手組:定向越野

收集實際出現的目標,排序後取前 N 個。

前往題目練習 →回報教學錯誤目標數 K:時間 O(WH+K log K),空間 O(K)(Python 緩衝 O(WH))。

這題在學什麼

輸入 W 行、每行 H 個字元,將非 0 格記錄為字母及其列行座標。

按字母由小到大排序,字母不保證由 a 開始或連續。

若目標不足 N 個,只輸出 Mission fail.;否則依序列出前 N 個座標。

Step-by-step animation

定向越野・按字母排序座標

回報動畫錯誤
步驟 1 / 3

掃描地圖

記下 q、b、a、z 的座標。

q:(0,0)
b:(0,2)
a:(1,0)
z:(1,1)
目標數
4
需求
3

Reference solution

回報程式錯誤

完整程式

#include <algorithm>
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int w, h, n;
    cin >> w >> h >> n;
    vector<pair<char, pair<int, int>>> v;
    for (int r = 0; r < w; r++)
        for (int c = 0; c < h; c++) {
            char x;
            cin >> x;
            if (x != '0')
                v.push_back({x, {r, c}});
        }
    sort(v.begin(), v.end());
    if ((int)v.size() < n)
        cout << "Mission fail.\n";
    else
        for (int i = 0; i < n; i++)
            cout << v[i].second.first << ' ' << v[i].second.second << '\n';
}

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

更多