본문 바로가기
백준

[백준] 8958번 - OX퀴즈

by 템닉___ 2024. 3. 20.

문제:

시도 횟수: 1번

처음 생각한 방법: O가 연속될때 콤보로 얻는 총 점수(sumScore)와, O가 나왔을때 얻는 점수(score)로 분리해서 생각함. 
그래서 문자열 중에서  O를 발견하는 경우 콤보점수와 점수를 모두 카운트해주고, 아닌경우 콤보를 제거해야하기에 score=0을 해줘야겠다고 생각함. 

내 코드:

#include <bits/stdc++.h>
using namespace std;

int main() {
    int T;
    cin >> T;
    string str;
    int sumScore = 0, score = 0;
    for(int i = 0; i < T; i++) {
        cin >> str;
        for(int j = 0; j < str.size(); j++) {
            if(str[j]=='O') {
                score = score + 1;
                sumScore = sumScore + score;
            }
            else {
                score = 0;
            }
        }
        cout << sumScore << endl;
        score = 0;
        sumScore = 0;
    }
}

모범답안: 

#include <iostream>
#include <string>

using namespace std;

int calculateScore(const string& quiz) {
    int score = 0;
    int consecutiveO = 0;

    for (char answer : quiz) {
        if (answer == 'O') {
            consecutiveO++;
            score += consecutiveO;
        } else {
            consecutiveO = 0;
        }
    }

    return score;
}

int main() {
    int testCases;
    cin >> testCases;
    cin.ignore(); // Ignore newline character after reading integer input

    for (int i = 0; i < testCases; ++i) {
        string quiz;
        getline(cin, quiz);
        cout << calculateScore(quiz) << endl;
    }

    return 0;
}

 

내 코드의 개선할 점: GPT가 짠 코드에서는, 로직은 전체적으로 비슷하지만 함수로 짰다. 로직이 이정도로 복잡해지면 함수로 빼는게 좋을 것 같기는 하다. 여기에서도 range based for 사용했다.

알고리즘 분류: 구현, 문자열

난이도: 브론즈 II

복습하면서 참고해본 블로그 목록:  X

 

'백준' 카테고리의 다른 글

[백준] 2752번 - 세수정렬  (0) 2024.03.20
[백준] 2577번 - 숫자의 개수  (0) 2024.03.20
[백준] 1152번 - 단어의 개수  (0) 2024.03.20
[백준] 2675번 - 문자열 반복  (0) 2024.03.20
[백준] 10809번 - 알파벳 찾기  (0) 2024.03.20