Home
Posts
Categories
Series
Tags
About
High Score Kit: Brute Force#2
Wire Cut
postedOn: 2024-4-11   updatedOn: 2024-4-11   includedIn: HighScoreKit
wordsCount: 531   readingTime: 3 mins   viewers:

Problem

In a power grid network composed of n transmission towers connected in a tree structure via wires, you are tasked with dividing the network into two parts by cutting one of the wires. The goal is to make the number of transmission towers in each part as equal as possible. Given the number of towers n and the wire connections wires, your function solution should return the smallest difference in the number of transmission towers between the two resulting networks after one cut.

Constraints

  • n is a natural number between 2 and 100, inclusive.
  • wires is a two-dimensional array of integers with a length of n-1.
  • Each element in wires is a pair [v1, v2], indicating that the transmission tower v1 is connected to tower v2 via a wire.
  • 1 ≤ v1 < v2 ≤ n.
  • The network always forms a single tree structure.

Example

n wires result
9 [[1,3],[2,3],[3,4],[4,5],[4,6],[4,7],[7,8],[7,9]] 3
4 [[1,2],[2,3],[3,4]] 0
7 [[1,2],[2,7],[3,7],[3,4],[4,5],[6,7]] 1

Explanation of Examples

  • Example 1:
    • There are 9 towers connected by 8 wires forming a tree. By choosing the optimal wire to cut, the difference in the number of towers between the two resulting networks can be minimized to 3.
  • Example 2:
    • With 4 towers connected in a straight line, cutting any of the wires results in two parts with an equal number of towers, resulting in a difference of 0.
  • Example 3:
    • A network of 7 towers can be split by the optimal wire cut to achieve a minimum tower difference of 1 between the two networks.

How to Approach?

Step1: Initialize variables in loop

Code

 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.util.ArrayList;
import java.util.List;

public class Solution {
    List<List<Integer>> adjList = new ArrayList<>();
    boolean[] visited;
    int totalTowers;
    int minDifference = Integer.MAX_VALUE;

    public int solution(int n, int[][] wires) {
        totalTowers = n;
        visited = new boolean[n + 1];
        
        // Initialize adjacency list for all nodes
        for (int i = 0; i <= n; i++) {
            adjList.add(new ArrayList<>());
        }
        
        // Construct the tree using adjacency list
        for (int[] wire : wires) {
            int v1 = wire[0];
            int v2 = wire[1];
            adjList.get(v1).add(v2);
            adjList.get(v2).add(v1);
        }
        
        // Try cutting each wire and calculate the difference
        for (int[] wire : wires) {
            int v1 = wire[0];
            int v2 = wire[1];
            
            // Remove the connection (cut the wire)
            adjList.get(v1).remove(Integer.valueOf(v2));
            adjList.get(v2).remove(Integer.valueOf(v1));
            
            // Reset visited array for new DFS
            visited = new boolean[n + 1];
            int towersInSubtree = countTowersDFS(v1);
            
            // Calculate difference in towers and update minDifference
            int difference = Math.abs(totalTowers - 2 * towersInSubtree);
            minDifference = Math.min(minDifference, difference);
            
            // Reconnect the wire
            adjList.get(v1).add(v2);
            adjList.get(v2).add(v1);
        }
        
        return minDifference;
    }

    private int countTowersDFS(int node) {
        visited[node] = true;
        int towersCount = 1; // Count the current node
        
        // Recurse on all adjacent nodes
        for (int adjNode : adjList.get(node)) {
            if (!visited[adjNode]) {
                towersCount += countTowersDFS(adjNode);
            }
        }
        
        return towersCount;
    }
}
Aaron Oh
고려대코딩개발협동조합 창단 멤버
Table of Contents
Related Posts
High Score Kit: Brute Force#1
Problem In the XX game, there is a fatigue system represented by non-negative integers, allowing players to explore dungeons by using a certain amount of fatigue. Each dungeon requires a “minimum required fatigue” to start exploring and consumes a certain amount of “fatigue” upon completion. For example, to explore a dungeon with a “minimum required fatigue” of 80 and a “consumption fatigue” of 20, a player’s current remaining fatigue must be at least 80, and it will decrease by 20 after exploring the dungeon.
2024-4-11
High Score Kit: Greedy#1
Problem Given a number, your task is to remove k digits from the number in such a way that the remaining digits form the largest possible number. The number is provided as a string number and the integer k represents the number of digits to remove. Your function solution should return the resulting largest number as a string.
2024-4-11
High Score Kit: DFS&BFS#2
Problem In the ROR game, you play on a team that competes to destroy the opposing team’s base first, making it advantageous to reach the enemy base as quickly as possible. Suppose you’re a team member and are located at position (row: 1, column: 1) on a 5x5 map, while the enemy base is at (row: 5, column: 5).
2024-4-11
High Score Kit: DFS&BFS#1
Problem You are given an array of non-negative integers and a target number. Your task is to find how many ways you can add and subtract the given numbers to achieve the target number. The order of numbers in the array must be preserved. For example, with the array [1, 1, 1, 1, 1], there are five ways to reach the target number 3:
2024-4-11
High Score Kit: Stack&Queue#2
Problem The Programmers team is currently performing feature improvement tasks. Each feature can only be released when its progress reaches 100%. However, since the development speed of each feature varies, it is possible for features developed later to be completed earlier. In such cases, a feature that is developed later will be released together with the feature in front of it that is scheduled for earlier release.
2024-4-10
High Score Kit: Stack&Queue#1
Problem Given an array arr consisting of integers ranging from 0 to 9, the task is to remove consecutive duplicates while preserving the order of the remaining elements. For instance, if arr = [1, 1, 3, 3, 0, 1, 1], the result should be [1, 3, 0, 1]. Similarly, for arr = [4, 4, 4, 3, 3], the result should be [4, 3].
2024-4-10