std::map で要素のカウント

atcoder.jp

を解いてて他の方のコードを見ていて知ったのでメモ.

この問題は最初に各文字で始まる文字列を数えておくと良いが,自分の実装では

#include <bits/stdc++.h>

using namespace std;

int main(){

    ios::sync_with_stdio(false);
    cin.tie(0);

    int n;
    cin >> n;
    int count[5] = {0};

    for (int i = 0; i < n; i++)
    {
        string s;
        cin >> s;
        if (s[0] == 'M')
        {
            count[0] += 1;
        }
        else if (s[0] == 'A')
        {
            count[1] += 1;
        }
        else if (s[0] == 'R')
        {
            count[2] += 1;
        }
        else if (s[0] == 'C')
        {
            count[3] += 1;
        }
        else if (s[0] == 'H')
        {
            count[4] += 1;
        }
        else
        {
            continue;
        }
    }

    for (int i = 0; i < n; i++)
    {
        cout << count[i] << endl;
    }

    return 0;
}

と愚直に書いていた.他の方のコードを参考にすると,std::map で書けるらしいと知ったので自分でも書いてみた.

#include <bits/stdc++.h>

using namespace std;

int main(){

    ios::sync_with_stdio(false);
    cin.tie(0);

    int n;
    cin >> n;
    map<char, int> count;
    for (int i = 0; i < n; i++)
    {
        string s;
        cin >> s;
        count[s[0]]++;
    }

    string s = "MARCH";
    for (int i = 0; i < n; i++)
    {
        cout << count[s[i]] << endl;
    }


    return 0;
}

std::map は平衡二分探索木で実装されているらしい.