In English, when many names appear in a list, they are often arranged in alphabetical order for easy reference. However, Wenwen feels that names of varying lengths mixed like this look untidy. Therefore, she decides to sort the names first by length, and then alphabetically if they have the same length. This way, when you list out the names, they will be arranged in a way that is narrow at the top and wide at the bottom, resembling a tower.
You're given several names, please sort them in Wenwen's way and output the result.
Sample Inputs/Outputs
Sample Input(s) | Sample Output(s) |
---|---|
The first line of input contains an integer N (0 < N <= 100). Following that are N lines, each containing an English name composed of letters, periods (.), hyphens (-), double quotes (“), and spaces. | The names in the input should first be sorted by length (including spaces and other symbols), and if lengths are the same, then alphabetically. |
5 Alexander Smith Mia Johnson Benjamin Lee Isabella Chang Oliver Taylor | Mia Johnson Benjamin Lee Oliver Taylor Isabella Chang Alexander Smith |
4 Ethan Baker April Adams Jacob White Emily Clark | April Adams Emily Clark Ethan Baker Jacob White |
Thought Process
After inputting N, perform a dummy getline once. This ensures that subsequent calls to getline will correctly receive the data.
Declare a Map<int, vector>, where the key represents the length of the string and the value represents the strings with that length. When receiving strings, determine their length and push them back into Map[length of string].
When outputting, use a for loop (auto it), then sort it.second, and then open another for loop to output the data in it.second (Vector) sequentially.
Sample Code-ZeroJudge N327: The Tower of Names
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
int main() {
int N;
cin >> N;
string s;
getline(cin, s);
map<int, vector<string>>MAP;
for (int i = 0; i<N; i++)
{
string str;
getline(cin, str);
vector<string>tmp;
int len = int(str.length());
tmp.assign(MAP[len].begin(), MAP[len].end());
tmp.push_back(str);
sort(tmp.begin(), tmp.end());
MAP[len].clear();
MAP[len].assign(tmp.begin(), tmp.end());
}
for (auto it:MAP)
{
vector<string>tmp = it.second;
for (int i = 0; i<tmp.size(); i++)
{
cout << tmp[i] << "\n";
}
}
}
//ZeroJudge N327
//Dr. SeanXD