a748簡單位置配對與數字多重集合交集

CPE:Master-Mind Hints (UVa 340)

在重複數字下正確分開 strong 與 weak。

前往題目練習 →回報教學錯誤每次猜測時間 O(N+10),額外空間 O(10)。

解題思路

先逐位置比較,完全相同的數量就是 strong。再分別統計答案和猜測的各數字次數,對每個數字取兩次數的最小值,總和得到不考慮位置時最多能配成的總對數。

總配對數已包含 strong,因此 weak=總配對−strong。這樣等價於先移走全部 strong 再配其餘數字,又不必實際標記每個位置。每局 N 個 0 的猜測只代表該局結束;下一個 N=0 才終止全部輸入。依 Game k: 和四個前導空白輸出 (S,W)。

Step-by-step animation

示意:答案 1,3,5,5;猜測 1,1,2,3

回報動畫錯誤
步驟 1 / 3

位置比較

只有第 1 格完全相同。

1=1
3≠1
5≠2
5≠3
strong
1

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
    int n, game = 0;
    while (cin >> n && n) {
        vector<int> a(n);
        int fa[10] = {};
        for (int &x : a) {
            cin >> x;
            ++fa[x];
        }
        cout << "Game " << ++game << ":\n";
        while (true) {
            vector<int> b(n);
            int fb[10] = {}, sum = 0, strong = 0;
            for (int i = 0; i < n; ++i) {
                cin >> b[i];
                sum += b[i];
                ++fb[b[i]];
                strong += a[i] == b[i];
            }
            if (!sum)
                break;
            int total = 0;
            for (int x = 1; x <= 9; ++x)
                total += min(fa[x], fb[x]);
            cout << "    (" << strong << ',' << total - strong << ")\n";
        }
    }
}

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

更多