a220簡單搜尋、貪心與進階解題

TOI 2022/04 新手組:比對卡片

對每張老師卡片枚舉學生位置,取同值距離的最小值。

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

這題在學什麼

老師第 i 張只與學生數字相同的位置比較,候選距離為 |i-j|。

枚舉全部學生卡片取最小距離,沒有同值就輸出 -1。

每張老師卡片獨立計算,學生卡片不會用掉,重複數字可以被多次匹配。

Step-by-step animation

比對卡片・每位置找最近同值

回報動畫錯誤
步驟 1 / 3

老師第一張 4

學生的 4 在第 2、4 張,距離 1、3,選 1。

距離1
距離3
answer[1]
1

Reference solution

回報程式錯誤

完整程式

#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    vector<int> a(n), b(n);
    for (int &x : a)
        cin >> x;
    for (int &x : b)
        cin >> x;
    for (int i = 0; i < n; i++) {
        int best = n;
        for (int j = 0; j < n; j++)
            if (a[i] == b[j])
                best = min(best, abs(i - j));
        cout << (i ? " " : "") << (best == n ? -1 : best);
    }
    cout << '\n';
}

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

更多