문제풀이(Problem Solving)

백준, BOJ, 4358번, 생태학 C++ [CPP] ★★

게임이 더 좋아 2022. 3. 26. 22:03
반응형
728x170

우선 Unordered 맵과 Ordered맵에 대한 정말 좋은 구분이라고 생각한다.

Unordered_map으로 만들었다면.. 정렬을 따로 해줘야했을 것이다.

 

 

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

 


 

#맞은 풀이

#include<bits/stdc++.h>

using namespace std;

string s;

//int와 int의 연산은 int가 나오므로 float으로 형변환하거나 처음부터 float과 연산
float num;

int main(){
    
    map<string, int> trees;

    while(getline(cin, s)){
        num++;
        
        //초기 값은 1
        if(trees.count(s) == 0){
            trees[s]=1;
        }
        else{
            trees[s]++;
        }
        
    }
    
    //소수점 자리 고정하는 부분
    cout << fixed;
    cout.precision(4);
    
    
    for(auto it = trees.begin(); it != trees.end(); it++ ){
        cout << it->first <<" "<< (it->second)* 100 / num << '\n';
    }
    
    
    return 0;
}

 

 

위의 주석처럼 3가지를 신경써주어야 한다.

 

또한 map 도 Iterator로 순회할 수 있기 때문에 ordered_map이라면 차례로 순회하면 key값이 사전순대로 정렬되어 출력된다.

 

반응형
그리드형