n개의 송전탑이 전선을 통해 하나의 트리 형태로 연결되어 있습니다. 당신은 이 전선들 중 하나를 끊어서 현재의 전력망 네트워크를 2개로 분할하려고 합니다. 이때, 두 전력망이 갖게 되는 송전탑의 개수를 최대한 비슷하게 맞추고자 합니다.
송전탑의 개수 n, 그리고 전선 정보 wires가 매개변수로 주어집니다. 전선들 중 하나를 끊어서 송전탑 개수가 가능한 비슷하도록 두 전력망으로 나누었을 때, 두 전력망이 가지고 있는 송전탑 개수의 차이(절대값)를 return 하도록 solution 함수를 완성해주세요.

| 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 |
(n - count)가 될 테니까 이를 이용하고자 했다.O(N)의 시간복잡도가 걸릴테니까 총 시간복잡도는 O(N^2)으로 추정되고, 이는 n이 최대 100이므로 알맞은 알고리즘이라고 생각된다.#include <string>
#include <vector>
using namespace std;
int dfs(int temp, int n, vector<int>& visited, vector<vector<bool>>& graph){
int count = 1;
visited[temp] = true;
for(int i = 1; i <= n; i++){
if(graph[temp][i] && !visited[i]){
count += dfs(i, n, visited, graph);
}
}
return count;
}
int solution(int n, vector<vector<int>> wires) {
int answer = n;
vector<vector<bool>> graph(n + 1, vector<bool>(n + 1, false));
for(vector<int> v : wires){
graph[v[0]][v[1]] = true;
graph[v[1]][v[0]] = true;
}
// edge 하나씩 끊어보면서 dfs로 개수 반환
for(vector<int> v : wires){
int x = v[0], y = v[1];
graph[x][y] = false;
graph[y][x] = false;
vector<int> visited(n + 1, false);
answer = min(answer, abs(n - 2 * dfs(x, n, visited, graph)));
graph[x][y] = true;
graph[y][x] = true;
}
return answer;
}