若 cnts[i]<cntg[i] 則代表 secret 中的 i 出現次數小於 guess 中的 i 出現次數,則對於 i 的 B 數量為 cnts[i];否則對於 i 的 B 數量為 cntg[i]。即對於每個數字 i,取 cnts[i] 和 cntg[i] 的最小值。將所有數字的 B 數量相加即為 cows 的數量。
from collections import Counter kase = 1 whileTrue: n = int(input()) if n == 0: break print(f"Game {kase}:") kase += 1 s = list(map(int, input().split())) # secret cnt_s0 = Counter(s) whileTrue: g = list(map(int, input().split())) # guess ifall(x == 0for x in g): break A = 0 cnt_s = cnt_s0.copy() cnt_g = Counter(g) for i inrange(n): if s[i] == g[i]: A += 1 cnt_s[s[i]] -= 1 cnt_g[g[i]] -= 1 B = sum(min(cnt_s[k], cnt_g[k]) for k in cnt_g) print(f" ({A},{B})")
#include<bits/stdc++.h> usingnamespace std; constint N = 1005; #define endl '\n'
intmain(){ ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int kase=1, n, A, B; int s[N], g[N], cnt_s0[10], cnt_s[10], cnt_g[10]; while (cin >> n && n) { cout << "Game " << kase++ << ":" << endl; for (int i = 0; i < n; i++) cin >> s[i]; // read secret memset(cnt_s0, 0, sizeof(cnt_s0)); for (int i = 0; i < n; i++) cnt_s0[s[i]]++; while (1) { for (int i = 0; i < n; i++) cin >> g[i]; // read guess bool flag = true; // check if all elements are 0 for (int i = 0; i < n; i++) if (g[i] != 0) flag = false; if (flag) break; memset(cnt_s, 0, sizeof(cnt_s)); memset(cnt_g, 0, sizeof(cnt_g)); A = B = 0; for (int i = 0; i < 10; i++) cnt_s[i] = cnt_s0[i]; // set cnt_s to cnt_s0, start from 0 for (int i = 0; i < n; i++){ if (s[i] == g[i]) { A++; cnt_s[s[i]]--; } else { cnt_g[g[i]]++; } } for (int i = 0; i < 10; i++) { // calculate B, start from 0 B += min(cnt_s[i], cnt_g[i]); } cout << " (" << A << "," << B << ")" << endl; } } return0; }