https://school.programmers.co.kr/learn/courses/30/lessons/86971
๋ฌธ์ ์ค๋ช
n๊ฐ์ ์ก์ ํ์ด ์ ์ ์ ํตํด ํ๋์ ํธ๋ฆฌ ํํ๋ก ์ฐ๊ฒฐ๋์ด ์์ต๋๋ค. ๋น์ ์ ์ด ์ ์ ๋ค ์ค ํ๋๋ฅผ ๋์ด์ ํ์ฌ์ ์ ๋ ฅ๋ง ๋คํธ์ํฌ๋ฅผ 2๊ฐ๋ก ๋ถํ ํ๋ ค๊ณ ํฉ๋๋ค. ์ด๋, ๋ ์ ๋ ฅ๋ง์ด ๊ฐ๊ฒ ๋๋ ์ก์ ํ์ ๊ฐ์๋ฅผ ์ต๋ํ ๋น์ทํ๊ฒ ๋ง์ถ๊ณ ์ ํฉ๋๋ค.
์ก์ ํ์ ๊ฐ์ n, ๊ทธ๋ฆฌ๊ณ ์ ์ ์ ๋ณด wires๊ฐ ๋งค๊ฐ๋ณ์๋ก ์ฃผ์ด์ง๋๋ค. ์ ์ ๋ค ์ค ํ๋๋ฅผ ๋์ด์ ์ก์ ํ ๊ฐ์๊ฐ ๊ฐ๋ฅํ ๋น์ทํ๋๋ก ๋ ์ ๋ ฅ๋ง์ผ๋ก ๋๋์์ ๋, ๋ ์ ๋ ฅ๋ง์ด ๊ฐ์ง๊ณ ์๋ ์ก์ ํ ๊ฐ์์ ์ฐจ์ด(์ ๋๊ฐ)๋ฅผ return ํ๋๋ก solution ํจ์๋ฅผ ์์ฑํด์ฃผ์ธ์.
์ ํ์ฌํญ
- n์ 2 ์ด์ 100 ์ดํ์ธ ์์ฐ์์ ๋๋ค.
- wires๋ ๊ธธ์ด๊ฐ n-1์ธ ์ ์ํ 2์ฐจ์ ๋ฐฐ์ด์
๋๋ค.
- wires์ ๊ฐ ์์๋ [v1, v2] 2๊ฐ์ ์์ฐ์๋ก ์ด๋ฃจ์ด์ ธ ์์ผ๋ฉฐ, ์ด๋ ์ ๋ ฅ๋ง์ v1๋ฒ ์ก์ ํ๊ณผ v2๋ฒ ์ก์ ํ์ด ์ ์ ์ผ๋ก ์ฐ๊ฒฐ๋์ด ์๋ค๋ ๊ฒ์ ์๋ฏธํฉ๋๋ค.
- 1 โค v1 < v2 โค n ์ ๋๋ค.
- ์ ๋ ฅ๋ง ๋คํธ์ํฌ๊ฐ ํ๋์ ํธ๋ฆฌ ํํ๊ฐ ์๋ ๊ฒฝ์ฐ๋ ์ ๋ ฅ์ผ๋ก ์ฃผ์ด์ง์ง ์์ต๋๋ค.
์ํ ๋ฌธ์ ์ธ๋ฐ dfs, bfs๋ก ํ ์ ์๋ค.
dfs๋ก ํ๋ ค๋ค๊ฐ ๋ญ๊ฐ ์ ์๋ผ์ bfs๋ก ํ์
๋์ ํ์ด
#include <string>
#include <vector>
#include <iostream>
#include <queue>
using namespace std;
int graph[101][101];
bool visited[101] = {0}; // ๋
ธ๋ ๋ฐฉ๋ฌธ
int N;
int bfs(int j){
queue<int> q;
q.push(j);
visited[j] = 1;
int re = 1;
while(!q.empty()){
int a = q.front();
q.pop();
for(int i=1; i<=N; ++i){
if(visited[i]==0 && graph[a][i]){
q.push(i);
visited[i] = 1;
re++;
}
}
}
return re;
}
int solution(int n, vector<vector<int>> wires) {
N = n;
int answer = 101;
for(int i=0; i<wires.size(); ++i){
graph[wires[i][0]][wires[i][1]] = 1;
graph[wires[i][1]][wires[i][0]] = 1;
}
for(int i=0; i<wires.size(); ++i){
vector<int> v;
fill(visited, visited+101, 0);
int x = wires[i][0];
int y = wires[i][1];
graph[x][y] = 0;
graph[y][x] = 0;
for(int j=1; j<=N; ++j){
int d=0;
if(!visited[j]){
d = bfs(j);
// cout << d<<" - ";
v.push_back(d);
}
}
int a = abs(v[0] - v[1]);
// cout << a <<"\n";
if(answer > a) answer = a;
if(answer == 0) break;
graph[x][y] = 1;
graph[y][x] = 1;
}
return answer;
}
'๐ ์๊ณ ๋ฆฌ์ฆ > Programmers' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[C++/PGS] Lv.0 : ๊ฒน์น๋ ์ ๋ถ์ ๊ธธ์ด (๊ตฌํ) (0) | 2023.05.27 |
---|---|
[C++/PGS] Lv.0 : ์ฐ์๋ ์์ ํฉ (๊ตฌํ) (0) | 2023.05.26 |
[C++/PGS] Lv.2 : ํผ๋ก๋ (์์ ํ์) (0) | 2023.05.26 |
[C++/PGS] Lv.2 : ๋ค๋ฆฌ๋ฅผ ์ง๋๋ ํธ๋ญ (ํ) (0) | 2023.04.13 |
[C++/PGS] Lv.3 : ๋ฒ ์คํธ์จ๋ฒ (ํด์ / map์ ๋ ฌ) (0) | 2023.04.13 |