9/15

chi·2024년 9월 14일

백준

목록 보기
18/20

1251

#include <stdio.h>
#include <string.h>

#define MAX_LEN 51

void reverse(char *str, int start, int end) {
    while (start < end) {
        char temp = str[start];
        str[start] = str[end];
        str[end] = temp;
        start++;
        end--;
    }
}

int main() {
    char word[MAX_LEN], result[MAX_LEN];
    scanf("%s", word);

    int len = strlen(word);
    strcpy(result, "z"); 
    
    for (int i = 1; i < len - 1; i++) {
        for (int j = i + 1; j < len; j++) {
            char temp[MAX_LEN];
            strcpy(temp, word);

            reverse(temp, 0, i - 1);
            reverse(temp, i, j - 1);
            reverse(temp, j, len - 1);
            
            if (strcmp(temp, result) < 0) {
                strcpy(result, temp);
            }
        }
    }

    printf("%s\n", result);
    return 0;
}

풀이
for문으로 단어를 세 부분으로 나눌 두 개의 인덱스 i, j를 결정
i는 첫 번째 파트의 끝이고 j는 두 번째 구간의 끝
각 파트를 뒤집은 후 다시 합쳐서 새로운 단어 생성
해당 단어가 지금까지 나온 단어들 중 앞에 오는지 비교해 업데이트함

1439

#include <stdio.h>
#include <string.h>

int main() {
    char S[1000001];
    scanf("%s", S);

    int count0 = 0; 
    int count1 = 0;  
    int len = strlen(S);
   
    if (S[0] == '0') {
        count0++;
    } else {
        count1++;
    }
    
    for (int i = 1; i < len; i++) {
        if (S[i] != S[i - 1]) {
            if (S[i] == '0') {
                count0++;
            } else {
                count1++;
            }
        }
    }

    int result = count0 < count1 ? count0 : count1;
    printf("%d\n", result);

    return 0;
}

풀이
문자열 S를 입력받음
처음 문자가 0이면 count0을 1 증가
1이면 count1을 1 증가시킴
문자열을 처음부터 끝까지 탐색하면서 현재 문자와 이전 문자가 다르면 그룹이 변한 것으로 해당 그룹에 맞게 카운트를 증가시킴
S[i]가 0이면 count0을 증가시키고 1이면 count1을 증가시킴
마지막으로 count0과 count1 중 작은 값 출력 = (최소 뒤집기 횟수)

0개의 댓글