티스토리 뷰
1. 문제
https://www.acmicpc.net/problem/14889
2. 풀이
백트래킹을 이용해 풀이한다.
- DFS를 이용해 한 사람씩 팀에 추가시키고 이를 boolean 배열에 저장한다(boolean[] visited)
- 선택한 사람의 수가 n/2인 경우, 즉 두 팀이 결성된 경우 두 팀의 점수차를 구한다.
- 두 팀의 점수차가 0인 경우 이미 최솟값이므로 프로그램을 종료한다.
3. 코드
import java.util.*;
import java.io.*;
class Main{
static int n;
static int[][] abilities;
static int min = Integer.MAX_VALUE;
static boolean[] visited;
public static int getScoreGap() {
int myScore = 0;
int yourScore = 0;
for(int i = 1; i <= n; i++) {
for(int j = i+1; j <= n; j++) {
if(visited[i] && visited[j]) {
myScore += abilities[i][j] + abilities[j][i];
}else if(!visited[i] && !visited[j]) {
yourScore += abilities[i][j] + abilities[j][i];
}
}
}
return Math.abs(myScore - yourScore);
}
public static void backtracking(int idx, int peopleCnt) {
if(peopleCnt == n/2) { // 한 팀이 완성된 경우
min = Math.min(min, getScoreGap());
if(min == 0) { // 0인 경우 더이상 탐색할 필요 없음
System.out.println(min);
System.exit(0);
}
return;
}
for(int i = idx + 1; i <= n; i++) {
visited[i] = true;
backtracking(i, peopleCnt + 1);
visited[i] = false;
}
}
public static void main (String[] args) throws java.lang.Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
abilities = new int[n+1][n+1];
visited = new boolean[n+1];
for(int i = 1; i <= n; i++) {
String[] input = br.readLine().split(" ");
for(int j = 1; j <= n; j++) {
abilities[i][j] = Integer.parseInt(input[j - 1]);
}
}
backtracking(0, 0);
System.out.println(min);
}
}
'알고리즘 > 백준' 카테고리의 다른 글
[JAVA/구현] 백준 14500 테트로미노 (0) | 2021.10.23 |
---|---|
[JAVA/BFS,구현] 백준 13460 구슬 탈출 2 (0) | 2021.10.22 |
[JAVA/DFS,BFS] 백준 14502 연구소 (0) | 2021.10.22 |
[JAVA/백트래킹] 백준 14888 연산자 끼워넣기 (0) | 2021.10.21 |
[JAVA/BFS] 백준 16236 아기 상어 (0) | 2021.10.21 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 라즈비안
- 아두이노
- java
- FTP
- dovecot
- 블루투스
- 2981
- c++
- DP
- ESP8266
- 백준
- 메일서버
- 스티커모으기2
- 프로그래머스
- 자바
- BFS
- 구슬 탈출2
- 키 순서
- mysql
- 리눅스
- 라즈베리파이
- hackerrank
- 집배원 한상덕
- git
- the pads
- 워드프레스
- dht11
- 합승 택시 요금
- 11503
- hc-06
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
글 보관함