본문 바로가기

알고리즘/순열

[JAVA] 백준 14889번: 스타트와 링크

문제

오늘은 스타트링크에 다니는 사람들이 모여서 축구를 해보려고 한다. 축구는 평일 오후에 하고 의무 참석도 아니다. 축구를 하기 위해 모인 사람은 총 N명이고 신기하게도 N은 짝수이다. 이제 N/2명으로 이루어진 스타트 팀과 링크 팀으로 사람들을 나눠야 한다.

BOJ를 운영하는 회사 답게 사람에게 번호를 1부터 N까지로 배정했고, 아래와 같은 능력치를 조사했다. 능력치 Sij는 i번 사람과 j번 사람이 같은 팀에 속했을 때, 팀에 더해지는 능력치이다. 팀의 능력치는 팀에 속한 모든 쌍의 능력치 Sij의 합이다. Sij는 Sji와 다를 수도 있으며, i번 사람과 j번 사람이 같은 팀에 속했을 때, 팀에 더해지는 능력치는 Sij와 Sji이다.

N=4이고, S가 아래와 같은 경우를 살펴보자.

 

  1 2 3
4   5 6
7 1   2
3 4 5  

예를 들어, 1, 2번이 스타트 팀, 3, 4번이 링크 팀에 속한 경우에 두 팀의 능력치는 아래와 같다.

  • 스타트 팀: S12 + S21 = 1 + 4 = 5
  • 링크 팀: S34 + S43 = 2 + 5 = 7

1, 3번이 스타트 팀, 2, 4번이 링크 팀에 속하면, 두 팀의 능력치는 아래와 같다.

  • 스타트 팀: S13 + S31 = 2 + 7 = 9
  • 링크 팀: S24 + S42 = 6 + 4 = 10

축구를 재미있게 하기 위해서 스타트 팀의 능력치와 링크 팀의 능력치의 차이를 최소로 하려고 한다. 위의 예제와 같은 경우에는 1, 4번이 스타트 팀, 2, 3번 팀이 링크 팀에 속하면 스타트 팀의 능력치는 6, 링크 팀의 능력치는 6이 되어서 차이가 0이 되고 이 값이 최소이다.

입력

첫째 줄에 N(4 ≤ N ≤ 20, N은 짝수)이 주어진다. 둘째 줄부터 N개의 줄에 S가 주어진다. 각 줄은 N개의 수로 이루어져 있고, i번 줄의 j번째 수는 Sij 이다. Sii는 항상 0이고, 나머지 Sij는 1보다 크거나 같고, 100보다 작거나 같은 정수이다.

출력

첫째 줄에 스타트 팀과 링크 팀의 능력치의 차이의 최솟값을 출력한다.

 

문제 풀이

문제를 푸는 방법은 간단하다.

1. 모든 인원을 2개의 그룹으로 나눈다.

2. 각각의 그룹에서 2명씩 짝을 지을 수 있는 경우의 수를 모두 구한다.

3. 짝을 지었다면 그 짝들의 능력치를 모두 구한다.

4. 그룹간의 능력치의 차이가 최소가 되는 값을 구한다.

 

예시 문제

6
0 1 2 3 4 5
1 0 2 3 4 5
1 2 0 3 4 5
1 2 3 0 4 5
1 2 3 4 0 5
1 2 3 4 5 0

 

1. 모든 인원을 2개의 그룹으로 나눈다.

{1,2,3}, {4,5,6}

...

 

2. 각각의 그룹을 2명으로 다시 나눠준다.

12 13 21 23 31 32
45 46 54 56 64 65        


3. 그룹별 능력치의 차가 최소가 되는 값을 구하자.

 

 

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;

public class baekjoon14889 {
    static int[][] info;
    static int n;
    static boolean[] visit;
    static boolean[] subVisit;
    static ArrayList<Integer> teamA = new ArrayList<>();
    static ArrayList<Integer> teamB = new ArrayList<>();
    static ArrayList<Integer> subTeamA = new ArrayList<>();
    static ArrayList<Integer> subTeamB = new ArrayList<>();
    static int teamARes = 0;
    static int teamBRes = 0;
    static ArrayList<Integer> resAry = new ArrayList<>();
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        info = new int[n][n];
        visit = new boolean[n];
        subVisit = new boolean[n];

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                info[i][j] = sc.nextInt();
            }
        }
              
        permutation(0,0);
        Collections.sort(resAry);
        System.out.println(resAry.get(0));
    }

    static void permutation(int point, int index){
        if (teamA.size() >= n/2) {
            for (int i = 0; i < n; i++) {
                if (!visit[i]) {
                    teamB.add(i);            
                }            
            }
            // toDo : teamA와 teamB 조합에서 능력치 차이를 계산하자.
            cal1(0);
            subVisit = new boolean[n];
            cal2(0);                        
            resAry.add(Math.abs(teamARes - teamBRes));
            teamARes = 0;
            teamBRes = 0;            
            teamB = new ArrayList<>();
            return;
        }    
        for (int i = point; i < n; i++) {
            if (!visit[i]) {
                visit[i] = true;
                teamA.add(i);
                permutation(i+1,index+1);
                teamA.remove(index);
                visit[i] = false;
            }
        }
    }
    static void cal(ArrayList<Integer> team, ArrayList<Integer> subTeam, int index, int teamRes){
        if (index==2) {
            System.out.println(subTeam);
            teamRes += info[subTeam.get(0)][subTeam.get(1)];
            return;
        }
        for (int i = 0; i < team.size(); i++) {
            if (!subVisit[i]) {
                subVisit[i]= true;                
                subTeam.add(team.get(i));                
                cal(team, subTeam, index+1, teamRes);
                subTeam.remove(index);
                subVisit[i]= false;
            }            
        }        
    }
    static void cal1(int index){
        if (index==2) {
            teamARes += info[subTeamA.get(0)][subTeamA.get(1)];
            return;
        }
        for (int i = 0; i < teamA.size(); i++) {
            if (!subVisit[i]) {
                subVisit[i]= true;                
                subTeamA.add(teamA.get(i));                
                cal1(index+1);
                subTeamA.remove(index);
                subVisit[i]= false;
            }            
        }        
    }
    static void cal2(int index){
        if (index==2) {
            teamBRes += info[subTeamB.get(0)][subTeamB.get(1)];
            return;
        }
        for (int i = 0; i < teamB.size(); i++) {
            if (!subVisit[i]) {
                subVisit[i]= true;                
                subTeamB.add(teamB.get(i));                
                cal2(index+1);
                subTeamB.remove(index);
                subVisit[i]= false;
            }            
        }        
    }
}

 

2개의 그룹을 나눠주는 방법에 대한 코드를 개선하였다.

cal 메소드 -> for문 2개로 변경.

 

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;

public class baekjoon14889 {
    static int[][] info;
    static int n;
    static boolean[] visit;
    static boolean[] subVisit;
    static ArrayList<Integer> teamA = new ArrayList<>();
    static ArrayList<Integer> teamB = new ArrayList<>();
    static ArrayList<Integer> subTeamA = new ArrayList<>();
    static ArrayList<Integer> subTeamB = new ArrayList<>();
    static int teamARes = 0;
    static int teamBRes = 0;
    static ArrayList<Integer> resAry = new ArrayList<>();
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        info = new int[n][n];
        visit = new boolean[n];
        subVisit = new boolean[n];

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                info[i][j] = sc.nextInt();
            }
        }
        // 두개의 그룹으로 나누고
        // {1,2,3} {4,5,6}
        // 각각의 그룹을 2명으로 다시 나누고
        // 12 13 21 23 31 32
        // 45 46 54 56 64 65        
        // 그룹별 능력치 차가 최소가 되는 값을 구하자        
        permutation(0,0);
        Collections.sort(resAry);
        System.out.println(resAry.get(0));
    }

    static void permutation(int point, int index){
        if (teamA.size() >= n/2) {
            for (int i = 0; i < n; i++) {
                if (!visit[i]) {
                    teamB.add(i);            
                }            
            }            
            // toDo : teamA와 teamB 조합에서 능력치 차이를 계산하자.
            for (int i = 0; i < n/2; i++) {
                for (int j = 0; j < n/2; j++) {
                    if (i != j) {
                        teamARes += info[teamA.get(i)][teamA.get(j)];
                        teamBRes += info[teamB.get(i)][teamB.get(j)];
                    } 
                }
            }
            resAry.add(Math.abs(teamARes - teamBRes));
            teamARes = 0;
            teamBRes = 0;
            teamB = new ArrayList<>();
            return;
        }    
        for (int i = point; i < n; i++) {
            if (!visit[i]) {
                visit[i] = true;
                teamA.add(i);
                permutation(i+1,index+1);
                teamA.remove(index);
                visit[i] = false;
            }
        }
    }
}

 

 

'알고리즘 > 순열' 카테고리의 다른 글

[JAVA] 백준 2580번: 스도쿠  (0) 2021.07.29
[JAVA] 백준 9663번: N-Queen  (0) 2021.07.26
[JAVA] 백준 14888번: 연산자 끼워넣기  (0) 2021.07.21
[JAVA] 백준 1339번: 단어수학  (0) 2021.07.20
[JAVA] 백준 2529번: 부등호  (0) 2021.07.19