백준 4358번 생태학

문제

생태학에서 나무의 분포도를 측정하는 것은 중요하다. 그러므로 당신은 미국 전역의 나무들이 주어졌을 때, 각 종이 전체에서 몇 %를 차지하는지 구하는 프로그램을 만들어야 한다.

문제풀이

사용한 알고리즘: map...

(1) (코드: 9~12)

 map<string, double>를 만들어 각 입력으로 들어오는 나무이름과 개수를 저장합니다.

(2) (코드: 15~21) 

 사실 map에 이미 사전순으로 저장 되어있습니다...
 map에 쌓아놓은 나무들을 iterator로 둘러보며 해당 이름과 백분율을 출력해줍니다.

주의할 점은, 입력 string name 을 받을 때 while(geline(cin , name))을 써주는 점입니다.

#include <bits/stdc++.h>
using namespace std;
int N;
string ss;
map<string, double> Howmany;
int main(){ios_base::sync_with_stdio(false); cout.tie(NULL); cin.tie(NULL);
while(getline(cin,ss)){
N+=1;
Howmany[ss]++;
}
cout<<fixed;
cout.precision(4);
for (auto iter=Howmany.begin(); iter!=Howmany.end();iter++){
string name = iter->first;
double n = iter->second;
n/=N;
n*=100.0;
cout << name << ' ' << n << '\n';
}
return 0;
}
view raw BOJ 4358.cpp hosted with ❤ by GitHub