熱門文章

2025年7月20日 星期日

ZeroJudge 解題筆記:b265. Q11286 - Conformity

作者:王一哲
日期:2025年7月20日


ZeroJudge 題目連結:b265. Q11286 - Conformity

解題想法


這個題目的中文敘述很奇怪。題目的意思應該是要統計各種課程組合的選課人數,例如
3
100 101 102 103 488
100 200 300 101 102
103 102 101 488 100
第 2、4 列是一樣的課程組合,因此答案為 2。另一筆範例測資
3
200 202 204 206 208
123 234 345 456 321
100 200 300 400 444
因為 2、3、4 列是不一樣的課程組合,各有 1 個人選擇這個組合,題目是將所有最多選課人數的課程組合都加起來,所以答案為 3。

Python 程式碼


使用時間約為 0.5 s,記憶體約為 10.1 MB,通過測試。
import sys
from collections import defaultdict

result = []
for line in sys.stdin:
    if not line.strip(): continue
    n = int(line)
    if n == 0: break
    cnt = defaultdict(int)
    for _ in range(n):
        course = tuple(sorted(list(map(int, sys.stdin.readline().split()))))
        cnt[course] += 1
    ans = imax = 0
    for v in cnt.values():
        if v > imax:
            ans = v; imax = v
        elif v == imax:
            ans += v
    result.append(f"{ans:d}\n")
sys.stdout.write("".join(result))


C++ 程式碼


使用時間約為 89 ms,記憶體約為 984 kB,通過測試。
#include <cstdio>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    int n;
    while(scanf("%d", &n) != EOF && n != 0) {
        map<vector<int>, int> cnt;
        for(int i=0; i<n; i++) {
            vector<int> course (5);
            for(int j=0; j<5; j++) scanf("%d", &course[j]);
            sort(course.begin(), course.end());
            cnt[course]++;
        }
        int ans = 0, imax = 0;
        for(auto it : cnt) {
            int v = it.second;
            if (v > imax) {
                ans = v; imax = v;
            } else if (v == imax) {
                ans += v;
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}


沒有留言:

張貼留言