熱門文章

2025年8月26日 星期二

ZeroJudge 解題筆記:d244. 一堆石頭

作者:王一哲
日期:2025年8月26日


ZeroJudge 題目連結:d244. 一堆石頭

解題想法


這題我是用字典計數,再用另一個集合記錄編號,如果某個編號的石頭有 3 個,將編號從集合中移n除,集合中最後只剩下一個編號,這個編號就是答案。如果是用 Python 解題,可以用 collections 函式庫中的 Counter,這個物件的速度更快。

Python 程式碼


使用時間約為 0.3 s,記憶體約為 25.9 MB,通過測試。
from collections import Counter

cnt = Counter(map(int, input().split()))  # 計數器
for k, v in cnt.items():  # 依序由 cnt 讀取 key 與 value
    if v == 2:  # 如果 v 等於 2
        print(k); break  # 印出 k,中止迴圈


使用時間約為 0.6 s,記憶體約為 25.6 MB,通過測試。
cnt = dict()  # 計數器
nums = set()  # 數字集合
for v in map(int, input().split()):  # 依序讀取值
    if v not in cnt:  # 如果 v 不在 cnt 之中
        cnt[v] = 1  # cnt[v] 等於 1
        nums.add(v)  # v 加入 nums
    else: cnt[v] += 1  # 如果 v 在 cnt 之中,cnt[v] 加 1
    if cnt[v] == 3: nums.remove(v)  # 如果 cnt[v] 等於 3,從 nums 中移除
print(*nums)  # nums 只剩一個值,就是答案


C++ 程式碼


使用時間約為 80 ms,記憶體約為 256 kB,通過測試。
#include <cstdio>
#include <unordered_map>
using namespace std;

int main() {
    unordered_map<int, int> cnt;  // 計數器
    int v;  // 數值
    while(scanf("%d", &v) != EOF) cnt[v]++;  // 讀取 v 直到 EOF 為止,cnt[v] 加 1
    for(auto it : cnt) {  // 從 cnt 依序讀取 key, value
        if (it.second == 2) {  // 如果 value 等於 2
            printf("%d\n", it.first);  // 印出 key
            break;  // 中止迴圈
        }
    }
    return 0;
}


沒有留言:

張貼留言