본문 바로가기
Problem Solving/Baekjoon

[백준] 16987 계란으로 계란치기 - Backtracking / Java

by graycode 2022. 9. 22.

 문제 링크

 

16987번: 계란으로 계란치기

원래 프로그래머의 기본 소양은 팔굽혀펴기를 단 한 개도 할 수 없는 것이라고 하지만 인범이는 3대 500을 넘기는 몇 안되는 프로그래머 중 한 명이다. 인범이는 BOJ에서 틀린 제출을 할 때마다 턱

www.acmicpc.net

 

 풀이 과정

 

 풀이 코드

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;

public class Main {

    static int n, max;
    static int[] hard, weight;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        StringTokenizer st;

        n = Integer.parseInt(br.readLine());

        hard = new int[n];
        weight = new int[n];

        for (int i = 0; i < n; i++) {
            st = new StringTokenizer(br.readLine());
            hard[i] = Integer.parseInt(st.nextToken());
            weight[i] = Integer.parseInt(st.nextToken());
        }

        recur(0);

        bw.write(String.valueOf(max));
        bw.flush();
    }

    private static void recur(int idx) {
        if (idx == n) {
            int cnt = 0;
            for (int i = 0; i < n; i++) {
                if (hard[i] <= 0)
                    cnt++;
            }

            max = Math.max(max, cnt);
            return;
        }

        if (hard[idx] <= 0)
            recur(idx + 1);
        else {
            boolean flag = false;
            for (int i = 0; i < n; i++) {
                if (i == idx || hard[i] <= 0)
                    continue;
                flag = true;

                hard[i] -= weight[idx];
                hard[idx] -= weight[i];
                recur(idx + 1);
                hard[i] += weight[idx];
                hard[idx] += weight[i];
            }

            if (flag == false)
                recur(idx + 1);
        }
    }

}

댓글