영원히 남는 기록, 재밌게 쓰자

SWEA [1289] 원재의 메모리 복구하기 D3 본문

Algorithm/SWEA

SWEA [1289] 원재의 메모리 복구하기 D3

youngjae-kim 2024. 2. 17. 15:46
728x90
반응형
 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

풀이

처음 문제가 이해가 안되었지만 쉽게 생각하면 초기화된 배열이 원래 배열로 돌아가기 위한 최소 변경 횟수를 구하는 문제였다.

 

배열을 돌면서

  • 초기화된 배열이 원래 배열의 i번째 비트의 값과 동일하면 변경할 필요가 없음
  • 다르다면 i 번째 ~ 끝까지 리셋된 배열의 값을 변경하고 count

 

정답 코드

package com.swea.D3.p1289;

import java.util.*;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        StringBuilder sb = new StringBuilder();

        int T = sc.nextInt();
        for (int t = 1; t <= T; t++) {
            sb.append("#" + t + " ");

            String bits = sc.next();

            int count = 0;
            int[] resetBits = new int[bits.length()];

            for (int i = 0; i < bits.length(); i++) {
                // 해당 번째 비트가 같으면 넘어감
                if (bits.charAt(i) - '0' == resetBits[i]) {
                    continue;
                } else {
                    // 다르면 해당 번째 비트에서 끝까지 원래 bit의 값으로 변경
                    count++;
                    for (int j = i; j < bits.length(); j++) {
                        resetBits[j] = bits.charAt(i) - '0';
                    }
                }
            }

            sb.append(count + "\n");
        }

        System.out.println(sb);
        sc.close();
    }
}
728x90
반응형