Algorithm/Data Structure

[BOJ 25325] S5 학생 인기도 측정 { C++ }

surimi🍥 2022. 7. 11. 18:14
반응형

25325번: 학생 인기도 측정

C++

  • map 대신 pair 사용.
#include <iostream>
#include <algorithm>
using namespace std;

void split(string S, pair<string, int> *P, int T)
{
    int cnt = 1, i = 0;
    for (char c : S)
        if (c == ' ')
            cnt++;

    string arr[cnt];

    for (char c : S)
        if (c == ' ')
            i++;
        else
            arr[i] += c;

    for (auto s : arr)
        for (int k = 0; k < T; k++)
            if (P[k].first == s)
                P[k].second++;
}

bool cmd(pair<string, int> A, pair<string, int> B)
{
    if (A.second == B.second)
        return (A.first < B.first);
    return (A.second > B.second);
}

int main()
{
    cin.tie(0)->sync_with_stdio(0);

    int T, i = -1;
    cin >> T;
    pair<string, int> P[T];
    string s;
    while (++i < T)
    {
        cin >> s;
        P[i] = {s, 0};
    }

    i = -1;
    cin.ignore();
    while (++i < T)
    {
        getline(cin, s);
        split(s, P, T);
    }
    sort(P, P + T, cmd);
    for (auto a : P)
        cout << a.first << " " << a.second << "\\n";
}

C++

  • unordered_map과 vector 사용.
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <vector>
using namespace std;

void split(string S, unordered_map<string, int> &M, int T)
{
    int cnt = 1, i = 0;
    for (char c : S)
        if (c == ' ')
            cnt++;

    string str[cnt];
    for (char c : S)
        if (c == ' ')
            i++;
        else
            str[i] += c;

    for (auto s : str)
        M[s]++;
}

bool cmd(pair<string, int> A, pair<string, int> B)
{
    if (A.second == B.second)
        return (A.first < B.first);
    return (A.second > B.second);
}

int main()
{
    cin.tie(0)->sync_with_stdio(0);

    int T, i = -1;
    cin >> T;
    unordered_map<string, int> M;
    string s;
    while (++i < T)
    {
        cin >> s;
        M[s] = 0;
    }

    i = -1;
    cin.ignore();
    while (++i < T)
    {
        getline(cin, s);
        split(s, M, T);
    }
    vector<pair<string, int>> V(M.begin(), M.end());
    sort(V.begin(), V.end(), cmd);
    for (auto a : V)
        cout << a.first << " " << a.second << "\\n";
}
반응형