백준 19941 java : Greedy Algorithms

magicdrill·2024년 11월 22일
0

백준 문제풀이

목록 보기
492/655

백준 19941 java : Greedy Algorithms

지금 당장의 순회에서 최고의 선택만 하면 된다.

import java.util.Scanner;

public class bj19941 {
    static Scanner scanner = new Scanner(System.in);
    static char[] table;
    static int N, K;

    public static void main(String[] args) {
        //그리디 알고리즘
        // 2810과 유사한거 같은데?
        inputData();
        System.out.println(findAnswer());

        scanner.close();
    }

    public static void inputData(){
        System.out.println("inputData()");
        int i;
        String data;

        N = scanner.nextInt();
        K = scanner.nextInt();
        table = new char[N + K];
        data = scanner.next();
        for(i = 0; i < N; i++){
            table[i] = data.charAt(i);
        }
    }

    public static int findAnswer(){
        System.out.println("findAnswer()");
        int answer = 0;
        int i, j;

        for(i = 0; i < N; i++)
        {
            if(table[i] == 'P')//사람이면?
            {
                for(j = i - K; j <= i + K; j++)
                {
                    if(j >= 0 && j < N){
                        if(table[j] == 'H')//햄버거면
                        {
                            table[j] = 'E';//햄버거 먹음
                            answer ++;
                            break;
                        }
                    }
                }

                System.out.println("answer : " + answer);
                //현재 테이블 상태 출력
                for(j = 0; j < N; j++){
                    System.out.print(table[j] + " ");
                }
                System.out.println();
            }
        }

        return answer;
    }
}

0개의 댓글