https://programmers.co.kr/learn/courses/30/lessons/86971
코딩테스트 연습 - 전력망을 둘로 나누기
9 [[1,3],[2,3],[3,4],[4,5],[4,6],[4,7],[7,8],[7,9]] 3 7 [[1,2],[2,7],[3,7],[3,4],[4,5],[6,7]] 1
programmers.co.kr
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stdlib.h>
#include <cmath>
using namespace std;
int map[101][101];
int used[101] = { 0 };
int cnt;
void dfs(int a, int n) {
used[a] = 1;
cnt++;
for (int i = 1; i <= n; i++) {
if (map[a][i]==1 && used[i] == 0) {
dfs(i, n);
}
}
}
int solution(int n, vector<vector<int>> wires) {
int answer = 999;
for (int i = 0; i < wires.size(); i++) {
int a = wires[i][0];
int b = wires[i][1];
map[a][b] = 1;
map[b][a] = 1;
}
for (int i = 0; i < wires.size(); i++) {
int a = wires[i][0];
int b = wires[i][1];
map[a][b] = 0;
map[b][a] = 0;
int group[2];
int flag = 0;
fill(used, used + n + 1, 0);
for (int j = 1; j <= n; j++) {
if (used[j] == 0) {
cnt = 0;
dfs(j, n);
group[flag] = cnt;
flag++;
}
}
map[a][b] = 1;
map[b][a] = 1;
answer = min(answer, abs(group[0] - group[1]));
}
return answer;
}
'APS > 프로그래머스' 카테고리의 다른 글
[2018 KAKAO BLIND RECRUITMENT] [1차] 셔틀버스 C++ (0) | 2021.12.17 |
---|---|
[그래프] 순위 C++ (0) | 2021.12.17 |
[2018 KAKAO BLIND RECRUITMENT] [1차] 뉴스 클러스터링 C++ (0) | 2021.12.17 |
[2017 카카오코드 본선]리틀 프렌즈 사천성 C++ (0) | 2021.12.09 |
[모든문제 LV2] 방금그곡 (0) | 2021.11.23 |