Problem-Solving/BOJ
[BOJ/백준][Gold4] 4358 : 생태학 (C++)
has2
2020. 12. 24. 14:58
https://www.acmicpc.net/problem/4358
4358번: 생태학
프로그램은 여러 줄로 이루어져 있으며, 한 줄에 하나의 나무 종 이름이 주어진다. 어떤 종 이름도 30글자를 넘지 않으며, 입력에는 최대 10,000개의 종이 주어지고 최대 1,000,000그루의 나무가 주어
www.acmicpc.net
[난이도] Gold4
[유형] Map, Trie
[풀이]
종의 이름을 key로 하는 (string,int) pair의 map을 만들어서
해당 종의 총 갯수를 구하면 된다.
나무 이름에 공백이 있을 수도 있으므로 한줄 전체를 입력으로 받아야 한다.
getline(cin,s) 함수를 이용하면 한줄을 단위로 입력받을 수 있다.
EOF 같은 경우 아래와 같이 처리해주면 파일이 끝날 때 while문을 빠져나가게 된다.
while(getline(cin,s)){
}
Trie로 풀면 더 빠른시간내에 해결할 수 있다고 한다.
#include <iostream>
#include <map>
#include <string>
#include <cmath>
using namespace std;
map<string,int> m;
int n;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
string s;
while(getline(cin,s)){
m[s]++;
n++;
}
for(auto k : m){
double b = 100*k.second / (double)n;
printf("%s %.4lf\n",k.first.c_str(),b);
}
}
https://github.com/has2/Problem-Solving/blob/master/boj-solved.ac/Gold4/4358.cpp