알고리즘/백준

백준 4351 Hay Points

등반 2021. 12. 27. 00:14

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

 

4351번: Hay Points

The first line of input contains 2 positive integers: m <= 1000, the number of words in the Hay Point dictionary, and n <= 100, the number of job descriptions. m lines follow; each contains a word (a string of up to 16 lower-case letters) and a dollar valu

www.acmicpc.net

정수 m, n이 첫 줄에 주어진다.

이후 m개의 줄에, 하나의 단어와 그 단어에 해당하는 점수가 공백을 두고 주어진다.

이후, n개의 문장(job description)이 '.'을 기준으로 구분해 주어진다.

단순히 문장의 각 단어마다 점수를 더하여 해결한다.

 

알아둘 것

cin 이후 getline을 받는 경우 이상한 값이들어가게 된다.

cin은 공백이나 줄바꿈을 기준으로 값을 입력받고, 입력 버퍼에 개행 문자(\n)를 남겨둔다.

getline은 개행문자가 나오기 전까지 입력을 받는다.

그러한 이유로

int n;
string s;
cin >> n;
getline(cin, s);

위와 같은 코드에서 n에 정수(ex : 9)를 입력(enter = '\n')하는 경우,

n에 9가 입력되고, 입력 버퍼에 개행 문자가 남게 된다.

이후 getline이 남아있던 개행 문자를 입력받고,

s에는 아무 값도 들어가지 않게 된다.

#include <iostream>
#define fio cin.tie(0)->sync_with_stdio(0)
using namespace std;

#include <map>
#include <sstream>
int main(){
    fio;
    int M, N; cin >> M >> N;
    map<string, int> hay_point;
    for(int i=0; i < M; i++){
        string S; int P; cin >> S >> P;
        hay_point[S] = P;
    }
    //
    cin.ignore();
    for(int i=0; i < N; i++){
        int score = 0;
        string S;
        while(1){
            getline(cin, S);
            if(S[0] == '.') break;
            stringstream ss(S);
            string tmp;
            while(ss >> tmp){
                if(hay_point.find(tmp) != hay_point.end()){//있다
                    score += hay_point[tmp];
                }else{
                    //
                }
            }
        }
        cout << score <<'\n';
    }
    return 0;
}

 

'알고리즘 > 백준' 카테고리의 다른 글

백준 5608 問題 2  (0) 2021.12.27
백준 4775 Spelling Be  (0) 2021.12.27
백준 4158 CD  (0) 2021.12.26
백준 2358 평행선  (0) 2021.12.26
백준 1417 국회의원 선거  (0) 2021.12.26