알고리즘 스터디 8월 2주차 문제3 (요리사)

문제#

  • 링크로 대체

풀이 및 주저리..

내일 있을 시험을 대비하면서 풀어 봤던 문제들을 정리하면서 다양한 방식들로 풀어보았다. 과거에는 문제를 보고 어떻게 풀어야겠다라고 생각이 들면 천천히 코드를 짜봤다면 이번에는 이건 조합! 이건 부분집합! 이렇게 생각을 하고 문제를 빠르게 풀어봤다. 특히나 앞에 말했던 두 부분을 매끄럽게 코드를 짜지 못하는 것 같아서 연습을 해보았다. 순열과 조합 그리고 부분집합 이렇게 세개는 확실하게 하면서 가야지 후에 문제들을 쉽게 풀 수 있을 것 같다.

코드

package ssafy.java.dfsbfs.pratice;

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

public class Solution_4102_Cook2 {
	static int N, map[][], answer;
	static boolean isSelected[];

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer stk = null;
		int iT = Integer.parseInt(br.readLine());
		for (int t = 1; t <= iT; t++) {
			N = Integer.parseInt(br.readLine());
			map = new int[N][N];
			isSelected = new boolean[N];
			answer = Integer.MAX_VALUE;
			for (int i = 0; i < N; i++) {
				stk = new StringTokenizer(br.readLine());
				for (int j = 0; j < N; j++) {
					map[i][j] = Integer.parseInt(stk.nextToken());
				}
			}
			getAnswer(0, 0);
			System.out.println("#" + t + " " + answer);
		}
	}

   // 아래는 조합방식
	private static void getAnswer(int cnt, int index) {
		if (cnt == N / 2) {
			int team1 = 0;
			int team2 = 0;
			for (int r = 0; r < N; r++) {
				for (int c = 0; c < N; c++) {
					if (isSelected[r] && isSelected[c]) {
						team1 += map[r][c];
					} else if (!isSelected[r] && !isSelected[c])
						team2 += map[r][c];
				}
			}
			answer = Math.min(answer, Math.abs(team1 - team2));
			return;
		}
		for (int i = index; i < N; i++) {
			if(isSelected[i]) continue;
			isSelected[i] = true;
			getAnswer(cnt + 1, i + 1);
			isSelected[i] = false;
		}
	}
   
   // 아래는 부분집합
   private static void getAnswer2(int cnt, int index) {
		if (cnt == N / 2) {
			int team1 = 0;
			int team2 = 0;
			for (int r = 0; r < N; r++) {
				for (int c = 0; c < N; c++) {
					if (isSelected[r] && isSelected[c]) {
						team1 += map[r][c];
					} else if (!isSelected[r] && !isSelected[c])
						team2 += map[r][c];
				}
			}
			answer = Math.min(answer, Math.abs(team1 - team2));
			return;
		}
		if(index == N)
			return;

		isSelected[index] = true;
		getAnswer(cnt + 1, index + 1);
		isSelected[index] = false;
		getAnswer(cnt, index + 1);
	}

}

기억에 남길 것!

© 2020 JunhoBaik, Built with Gatsby