• 카테고리

    질문 & 답변
  • 세부 분야

    알고리즘 · 자료구조

  • 해결 여부

    미해결

바둑대회 질문드립니다.

23.07.26 21:15 작성 조회수 158

0

import java.util.*;

import javax.security.auth.Subject;

import java.awt.List;
import java.io.*;

class Main {
	public static boolean[] visit;
	public static int len,answer=Integer.MAX_VALUE;
	public int solution(int[][] cans){
			
		len=cans.length;
		
		visit =new boolean[len];
		
		dfs(0,0,cans);
		return answer;
	}
	public static void dfs(int L,int s,int[][] cans) {
		if(L==len/2) {
			ArrayList<Integer> a = new ArrayList<>();
			ArrayList<Integer> b = new ArrayList<>();
			for(int i=0; i<len; i++) {
				if(visit[i]) a.add(i);
				else b.add(i);
			}
			int sum1=0,sum2=0;
			for(int i=0; i<L; i++) {
				sum1+=cans[a.get(i)][0];
				sum2+=cans[b.get(i)][1];
			}
			answer =Math.min(answer, Math.abs(sum1-sum2));
		}
		else {
			for(int i=s; i<len; i++) {
				visit[i] = true;
				dfs(L+1, i+1,cans);
				visit[i] = false;
			}
		}
	}
	public static void main(String[] args){
		Main T = new Main();
		System.out.println(T.solution(new int[][]{{87, 84}, {66, 78}, {94, 94}, {93, 87}, {72, 92}, {78, 63}}));
		System.out.println(T.solution(new int[][]{{10, 20}, {15, 25}, {35, 23}, {55, 20}}));
		System.out.println(T.solution(new int[][]{{11, 27}, {16, 21}, {35, 21}, {52, 21}, {25, 33},{25, 32}, {37, 59}, {33, 47}}));
	}
}

이렇게 작성했는데 마지막 테스트 케이스가 1이 아닌 0이 나옵니다. 어디가 잘못된건지 모르겠습니다.

 

 

 

 

답변 1

답변을 작성해보세요.

0

안녕하세요^^

answer를 static 전역으로 잡아서 그렇습니다. solution에서 매번 초기화하세요.

public int solution(int[][] cans){
	answer=Integer.MAX_VALUE;	
	len=cans.length;
		
	visit =new boolean[len];
		
	dfs(0,0,cans);
	return answer;
}