ZeroJudge C012: Tell me the frequencies!

Given a string of text, please find the frequency of each character.

Sample Inputs/Outputs

Sample Input(s)Sample Output(s)
EOF inputs: each test case consists of a single line of text with a maximum length of 1000 characters.For each line of input, please output the ASCII value of each character along with its frequency of occurrence. Output them in ascending order of frequency. If there are two or more characters with the same frequency, output the one with the larger ASCII value first. Leave a blank line between test cases.
AAABBC
122333
67 1
66 2
65 3

49 1
50 2
51 3

Thought Process

Since there might be spaces in the input, you should use getline for input. You can use a Map to record the frequency of each character.

After determining the frequencies, use auto to iterate over the Map in a for loop. Then, create another Map to store the answer, where the key is the frequency and the value is a vector used to store multiple characters while sorting them.

Every time, assign the vector from the answer map to a temporary vector. Then, push the current character into this temporary vector. After that, sort the temporary vector. Finally, reassign the temporary vector back to the value in the answer map.

Finally, iterate through the answer map using an auto loop. Inside, iterate through the vector in the map's value using another loop, and output the ASCII code of the character.

Sample Code-ZeroJudge C012: Tell me the frequencies!

#include <iostream>
#include <map>
#include <algorithm>
#include <vector>
using namespace std;

int main() {
    string str;
    while (getline(cin, str))
    {
        map<int, int>MAP;
        for (int i = 0; i<str.length(); i++)
        {
            MAP[float(str[i])]++;
        }
        map<int, vector<int>>ans;
        for (auto it:MAP)
        {
            vector<int>tmp;
            tmp.assign(ans[it.second].begin(), ans[it.second].end());
            tmp.push_back(it.first);
            sort(tmp.begin(), tmp.end());
            reverse(tmp.begin(), tmp.end());
            ans[it.second].assign(tmp.begin(), tmp.end());
        }
        for (auto it:ans)
        {
            vector<int>tmp = it.second;
            for (int i = 0; i<tmp.size(); i++)
            {
                cout << tmp[i] << " " << it.first << "\n";
            }
            cout << "\n";
        }
    }
}

//ZeroJudge C012
//Dr. SeanXD

Comments