Developing Myself Everyday
article thumbnail
 

17471번: 게리맨더링

선거구를 [1, 4], [2, 3, 5, 6]으로 나누면 각 선거구의 인구는 9, 8이 된다. 인구 차이는 1이고, 이 값보다 더 작은 값으로 선거구를 나눌 수는 없다.

www.acmicpc.net

문제

백준시의 시장 최백준은 지난 몇 년간 게리맨더링을 통해서 자신의 당에게 유리하게 선거구를 획정했다. 견제할 권력이 없어진 최백준은 권력을 매우 부당하게 행사했고, 심지어는 시의 이름도 백준시로 변경했다. 이번 선거에서는 최대한 공평하게 선거구를 획정하려고 한다.

백준시는 N개의 구역으로 나누어져 있고, 구역은 1번부터 N번까지 번호가 매겨져 있다. 구역을 두 개의 선거구로 나눠야 하고, 각 구역은 두 선거구 중 하나에 포함되어야 한다. 선거구는 구역을 적어도 하나 포함해야 하고, 한 선거구에 포함되어 있는 구역은 모두 연결되어 있어야 한다. 구역 A에서 인접한 구역을 통해서 구역 B로 갈 수 있을 때, 두 구역은 연결되어 있다고 한다. 중간에 통하는 인접한 구역은 0개 이상이어야 하고, 모두 같은 선거구에 포함된 구역이어야 한다.

아래 그림은 6개의 구역이 있는 것이고, 인접한 구역은 선으로 연결되어 있다.

 

아래는 백준시를 두 선거구로 나눈 4가지 방법이며, 가능한 방법과 불가능한 방법에 대한 예시이다.

공평하게 선거구를 나누기 위해 두 선거구에 포함된 인구의 차이를 최소로 하려고 한다. 백준시의 정보가 주어졌을 때, 인구 차이의 최솟값을 구해보자.

입력

첫째 줄에 구역의 개수 N이 주어진다. 둘째 줄에 구역의 인구가 1번 구역부터 N번 구역까지 순서대로 주어진다. 인구는 공백으로 구분되어져 있다.

셋째 줄부터 N개의 줄에 각 구역과 인접한 구역의 정보가 주어진다. 각 정보의 첫 번째 정수는 그 구역과 인접한 구역의 수이고, 이후 인접한 구역의 번호가 주어진다. 모든 값은 정수로 구분되어져 있다.

구역 A가 구역 B와 인접하면 구역 B도 구역 A와 인접하다. 인접한 구역이 없을 수도 있다.

출력

첫째 줄에 백준시를 두 선거구로 나누었을 때, 두 선거구의 인구 차이의 최솟값을 출력한다. 두 선거구로 나눌 수 없는 경우에는 -1을 출력한다.


 

 

출력

이 문제에서 주어진 구역의 크기는 10으로 매우 작습니다. 그렇기에 조합을 이용해 두 선거구로 나눌 수 있는 두 선거구의 조합을 구하고 이를 브루트포스하게 해결하면 됩니다.

 저는 조합으로 하나의 그룹을 구하고, 그에 속하지 않은 지역구를 다른 그룹으로 분류했습니다. 그리고 BFS를 사용해서 그룹을 탐색한 다음 그룹을 전부 탐색한 상황에만 인구수를 구하도록 했습니다.

 

자세한 설명은 주석으로 첨부했습니다.

 

Kotlin

import java.util.*
import kotlin.math.abs
import kotlin.math.min

lateinit var graph : List<MutableList<Int>>
lateinit var population : List<Int>
var ans = Int.MAX_VALUE

fun main() = with(System.`in`.bufferedReader()) {

    val n = readLine().toInt()
    population = readLine().split(" ").map { it.toInt() }

    graph = List(n + 1) { mutableListOf<Int>() }

    // 각 지역구의 경로 설정
    repeat(n) { start ->
        val line = readLine().split(" ").map { it.toInt() }

        val adjacentNum = line[0]

        for (i in 1..adjacentNum) {
            val end = line[i]

            graph[start + 1].add(end)
        }
    }
    
    // 1 ~ n / 2까지 하나의 그룹의 개수를 정하고 탐색
    (1..n / 2).forEach {
        combination(1, it, n)
    }

    if (ans == Int.MAX_VALUE)
        println(-1)
    else
        println(ans)
}

// 조합으로 하나의 그룹을 구함
val group = mutableListOf<Int>()
fun combination(start: Int, target: Int, n: Int) {
    if (target == 0) {
        bfs(n, group)
        return
    }

    for (i in start..n) {
        group.add(i)
        combination(i + 1, target - 1, n)
        group.removeAt(group.lastIndex)
    }
}

// 그룹을 탐색할 수 있는지 BFS로 확인
fun bfs(n: Int, group: MutableList<Int>) {
    val group1 = group.toMutableList()
    val group2 = mutableListOf<Int>()

    // 그룹을 나눔
    for (i in 1..n) {
        if (!group1.contains(i)) group2.add(i)
    }

    val queue : Queue<Int> = LinkedList()

    // 초기값 설정
    var temp = group1.removeFirst()
    var group1Population = population[temp - 1]
    queue.add(temp)

    while (queue.isNotEmpty()) {
        val now = queue.poll()

        for (next in graph[now]) {
            // 다음 경로가 그룹에 속하지 않다면 PASS
            if (!group1.contains(next)) continue

            // 속한다면 중복을 막기위해 해당 지역구를 제거하고 추가
            group1.remove(next)
            group1Population += population[next - 1]
            queue.add(next)
        }
    }

    // 그룹이 비어있지 않다면 전부 탐색하지 못했음으로 탈출
    if (group1.isNotEmpty()) return

    temp = group2.removeFirst()
    var group2Population = population[temp - 1]
    queue.add(temp)

    while (queue.isNotEmpty()) {
        val now = queue.poll()

        for (next in graph[now]) {
            if (!group2.contains(next)) continue

            group2.remove(next)
            group2Population += population[next - 1]
            queue.add(next)
        }
    }

    if (group2.isNotEmpty()) return

    ans = min(ans, abs(group1Population - group2Population))
}

 

Java

import java.io.*;
import java.util.*;

public class Main {


    static ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
    static int[] population;
    static int ans = Integer.MAX_VALUE;

    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(bf.readLine());

        int n = Integer.parseInt(st.nextToken());

        st = new StringTokenizer(bf.readLine());
        population = new int[n + 1];
        for (int i = 1; i <= n; i++) {
            population[i] = Integer.parseInt(st.nextToken());
        }

        graph.add(new ArrayList<>());

        for (int start = 1; start <= n; start++) {
            graph.add(new ArrayList<>());
            st = new StringTokenizer(bf.readLine());

            int adjacentNum = Integer.parseInt(st.nextToken());

            for (int i = 1; i <= adjacentNum; i++) {
                int end = Integer.parseInt(st.nextToken());

                graph.get(start).add(end);
            }
        }

        for (int i = 1; i <= n / 2; i++) {
            combination(1, i, n);
        }

        if (ans == Integer.MAX_VALUE)
            System.out.println(-1);
        else
            System.out.println(ans);
    }

    static List<Integer> group = new ArrayList<>();
    static void combination(int start, int target, int n) {
        if (target == 0) {
            bfs(n, group);
        }

        for (int i = start; i <= n; i++) {
            group.add(i);
            combination(i + 1, target - 1, n);
            group.remove(group.size() - 1);
        }
    }

    static void bfs(int n, List<Integer> group) {
        List<Integer> group1 = new ArrayList<>(group);
        List<Integer> group2 = new ArrayList<>();

        for (int i = 1; i <= n; i++) {
            if (!group1.contains(i)) group2.add(i);
        }

        Queue<Integer> queue = new LinkedList<>();

        int temp = group1.remove(0);
        int group1Population = population[temp];
        queue.add(temp);

        while (!queue.isEmpty()) {
            int now = queue.poll();

            for (int next : graph.get(now)) {
                if (!group1.contains(next)) continue;

                group1.remove(Integer.valueOf(next));
                group1Population += population[next];
                queue.add(next);
            }
        }

        if (!group1.isEmpty()) return;

        temp = group2.remove(0);
        int group2Population = population[temp];
        queue.add(temp);

        while (!queue.isEmpty()) {
            int now = queue.poll();

            for (int next : graph.get(now)) {
                if (!group2.contains(next)) continue;

                group2.remove(Integer.valueOf(next));
                group2Population += population[next];
                queue.add(next);
            }
        }

        if (!group2.isEmpty()) return;

        ans = Math.min(ans, Math.abs(group1Population - group2Population));
    }
}
profile

Developing Myself Everyday

@배준형

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!