b151中等

108 北一區資訊學科能力競賽(2019)|電話民調計票

逐行保留原始票字串,長度恰N、只含0與*、星號不超過M才是有效票。

解題思路

逐行保留原始票字串,長度恰N、只含0與*、星號不超過M才是有效票。

有效票的每個*使對應候選人加一票;整張先驗證,避免無效票的部分票數流入統計。

最後按(-票數,姓名ASCII字典序)排序全部候選人,包括零票者。

時間 O(PN+N log N),空間 O(N)加票字串及姓名。

Step-by-step animation

教學小例:先驗票再累計與排序

回報動畫錯誤
步驟 1 / 3

候選A,B,M=1

票*0有效,A加1

票*0有效,A加1
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    int n, m, p;
    cin >> n >> m;
    vector<string> a(n);
    for (auto &s : a)
        cin >> s;
    cin >> p;
    string s;
    getline(cin, s);
    vector<int> cnt(n);
    while (p--) {
        getline(cin, s);
        if ((int)s.size() != n || s.find_first_not_of("0*") != string::npos ||
            count(s.begin(), s.end(), '*') > m)
            continue;
        for (int i = 0; i < n; i++)
            cnt[i] += s[i] == '*';
    }
    vector<int> ids(n);
    iota(ids.begin(), ids.end(), 0);
    sort(ids.begin(), ids.end(), [&](int i, int j) {
        return cnt[i] != cnt[j] ? cnt[i] > cnt[j] : a[i] < a[j];
    });
    for (int i : ids)
        cout << a[i] << ' ' << cnt[i] << '\n';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多