日期:2026年3月30日
ZeroJudge 題目連結:d045. 11222 - Only I did it!
解題想法
我是用集合處理這題。先將三人解的題號分別存入集合 $a, b, c$,只有第一個人解出來的題目就是 $a$ 對 $b, c$ 的聯集取差集,只有第二個人解出來的題目就是 $b$ 對 $c, a$ 的聯集取差集,只有第三個人解出來的題目就是 $c$ 對 $a, b$ 的聯集取差集。分別計算三個差集的長度,輸出最長的差集對應的朋友編號、差集長度與題號。
Python 程式碼
使用時間約為 9 ms,記憶體約為 3.5 MB,通過測試。
T = int(input())
for t in range(1, T+1):
print(f"Case #{t:d}:")
a = set(tuple(map(int, input().split()))[1:])
b = set(tuple(map(int, input().split()))[1:])
c = set(tuple(map(int, input().split()))[1:])
a_bc = a.difference(b.union(c))
b_ca = b.difference(c.union(a))
c_ab = c.difference(a.union(b))
m, n, p = len(a_bc), len(b_ca), len(c_ab)
imax = max(m, n, p)
if m == imax: print(1, m, *sorted(a_bc))
if n == imax: print(2, n, *sorted(b_ca))
if p == imax: print(3, p, *sorted(c_ab))
C++ 程式碼
使用時間約為 3 ms,記憶體約為 560 kB,通過測試。
#include <cstdio>
#include <set>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int T; scanf("%d", &T);
for(int t=1; t<=T; t++) {
printf("Case #%d:\n", t);
vector<set<int>> problems (3); // 三人解的題號
for(int i=0; i<3; i++) {
int n; scanf("%d", &n); // 題數
for(int j=0; j<n; j++) {
int q; scanf("%d", &q);
problems[i].insert(q);
}
}
vector<set<int>> unique (3); // 三人解出另外兩個人沒解的題號
for(int i=0; i<3; i++) {
set<int> tmp = problems[i]; // 第 i 個人解出的題號
for(int j=0; j<3; j++) {
if (i == j) continue; // 跳過自己
for(int q : problems[j]) tmp.erase(q);
}
unique[i] = tmp;
}
int imax = 0;
vector<int> ans;
for(int i=0; i<3; i++) {
set<int> uni = unique[i];
int n = (int)uni.size();
if (n > imax) {
imax = n;
ans.clear();
ans.push_back(i);
} else if (n == imax) {
ans.push_back(i);
}
}
for(int a : ans) {
printf("%d %d", a+1, imax);
for(int q : unique[a]) printf(" %d", q);
puts("");
}
}
return 0;
}
沒有留言:
張貼留言