Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Trò chơi lật thẻ C++ (Card Flipping Game)

N thẻ, mỗi mặt một số dương. Có thể lật bất kỳ thẻ nào. Chọn 1 thẻ, nếu số mặt sau (X) không xuất hiện ở mặt trước của thẻ nào → X là "good". Tìm good number nhỏ nhất.

Ví dụ

Input - fronts=[1,2,4,4,7], backs=[1,3,4,1,3] Output - 2

Giải thích - Lật thẻ 2: fronts=[1,3,4,4,7], backs=[1,2,4,1,3]. Chọn thẻ 2, mặt sau=2 không có ở fronts → 2 là good.

Phương pháp tiếp cận

  • Số xuất hiện cả 2 mặt cùng thẻ (fronts[i]==backs[i]) → không bao giờ good (vào set cấm)
  • Trong các số còn lại, tìm min của fronts và backs không trong set cấm

Ví dụ code C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
    int flipgame(vector<int>& fronts, vector<int>& backs) {
        set<int> banned;
        int n = fronts.size();
        for (int i = 0; i < n; i++)
            if (fronts[i] == backs[i]) banned.insert(fronts[i]);

        int ret = INT_MAX;
        for (int i = 0; i < n; i++)
            if (!banned.count(fronts[i])) ret = min(ret, fronts[i]);
        for (int i = 0; i < n; i++)
            if (!banned.count(backs[i])) ret = min(ret, backs[i]);

        return ret == INT_MAX ? 0 : ret;
    }
};

int main() {
    vector<int> v1 = {1,2,4,4,7};
    vector<int> v2 = {1,3,4,1,3};
    Solution ob;
    cout << ob.flipgame(v1, v2);
    return 0;
}

Kết quả

2