선택은 나의 것

[BOJ 백준] 4358번 생태학 본문

☽ Algorithm/BOJ

[BOJ 백준] 4358번 생태학

Algoribi 2020. 9. 1. 14:28

문제

BOJ 4358 : www.acmicpc.net/problem/4358

 

4358번: 생태학

프로그램은 여러 줄로 이루어져 있으며, 한 줄에 하나의 나무 종 이름이 주어진다. 어떤 종 이름도 30글자를 넘지 않으며, 입력에는 최대 10,000개의 종이 주어지고 최대 1,000,000그루의 나무가 주어

www.acmicpc.net

접근

map을 사용하여 중복으로 등장하는 나무의 그루 수를 세준다. map은 오름차순 정렬이 되어있기 때문에 순차적으로 출력하며 몇%를 차지하는지 계산해주면 된다.

코드

#include <iostream>
#include <map>
#include <string>

using namespace std;

int main() {
    string s;
    map<string, double> m;
    double counter = 0;
    while (getline(cin, s)) {
        counter++;
        if (m.find(s) == m.end())
            m.insert(make_pair(s, 1));
        else
            m[s]++;
    }
    cout.setf(ios::fixed);
    cout.precision(4);
    for (auto it = m.begin(); it != m.end(); it++) {
        double num = it->second / counter * 100;
        cout << it->first << " " << num << "\n";
    }
}

 

깃 허브 주소 : https://github.com/algoribi/algorithm-study

Comments