문제

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

걸린 시간

01 : 05 : 29

풀이

C++

#include <bits/stdc++.h>
#define fastio ios::sync_with_stdio(0), cin.tie(0)
#define all(c) c.begin(), c.end()
#define INF 1e9
typedef long long ll;
typedef unsigned long long ull;
using namespace std;

int main(){
    fastio;
    string p;
    getline(cin, p);
    int s;
    cin >> s;
    vector<int> a(26, 0);
    for(int i = 0; i < 26; i++){
        cin >> a[i];
    }
    vector<string> w;
    istringstream ss(p);
    string buf;
    while(getline(ss, buf, ' ')){
        if(buf != "") w.push_back(buf);
    }
    if(w.size()-1 > s){
        cout << -1 << "\n";
        return 0;
    }
    string ans = "";
    char last;
    for(int i = 0; i < w.size(); i++){
        last = ' ';
        for(int j = 0; j < w[i].size(); j++){
            if(j == 0) ans += toupper(w[i][j]);
            if(last == w[i][j]) continue;
            a[tolower(w[i][j])-'a']--;
            last = w[i][j];
        }
    }
    last = ' ';
    for(char c : ans){
        if(last == c) continue;
        a[tolower(c)-'a']--;
        last = c;
    }
    if(*min_element(all(a)) < 0){
        cout << -1 << "\n";
        return 0;
    }
    cout << ans << "\n";
    return 0;
}

시의 단어를 기준으로 나누면 시의 제목을 가져오는 것도 편리하고 스페이스바와 알파벳을 따로 처리할 수 있어 istringstream 을 이용해 공백을 기준으로 문자열을 분리했다.

하지만 계속 61% 에서 틀렸습니다를 받았는데 이유는 공백 문자 하나를 기준으로 나누다 보니 비어있는 문자열까지 저장되어 필요한 스페이스바의 최소 개수가 재대로 구해지지 않았던 것이었다. 오랜 삽질 끝에 문자열인지 체크하는 조건을 넣어주고 나서야 ac 를 받을 수 있었다.

'Baekjoon' 카테고리의 다른 글

Baekjoon 2457번 공주님의 정원  (0) 2021.05.04
Baekjoon 1629번 곱셈  (0) 2021.04.25
Baekjoon 1744번 수 묶기  (0) 2021.04.18
Baekjoon 9663번 N-Queen  (0) 2021.04.14
Baekjoon 10610번 30  (0) 2021.03.21

댓글