๐Ÿ’  Cpp/[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๊ณ ๋“์  Kit

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์ „๋ ฅ๋ง์„ ๋‘˜๋กœ ๋‚˜๋ˆ„๊ธฐ (level2)

์„ ๋‹ฌ 2025. 1. 17. 22:05
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

n๊ฐœ์˜ ์†ก์ „ํƒ‘์ด ์ „์„ ์„ ํ†ตํ•ด ํ•˜๋‚˜์˜ ํŠธ๋ฆฌ ํ˜•ํƒœ๋กœ ์—ฐ๊ฒฐ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค.

๋‹น์‹ ์€ ์ด ์ „์„ ๋“ค ์ค‘ ํ•˜๋‚˜๋ฅผ ๋Š์–ด์„œ ํ˜„์žฌ์˜ ์ „๋ ฅ๋ง ๋„คํŠธ์›Œํฌ๋ฅผ 2๊ฐœ๋กœ ๋ถ„ํ• ํ•˜๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค.

์ด๋•Œ, ๋‘ ์ „๋ ฅ๋ง์ด ๊ฐ–๊ฒŒ ๋˜๋Š” ์†ก์ „ํƒ‘์˜ ๊ฐœ์ˆ˜๋ฅผ ์ตœ๋Œ€ํ•œ ๋น„์Šทํ•˜๊ฒŒ ๋งž์ถ”๊ณ ์ž ํ•ฉ๋‹ˆ๋‹ค.

 

์†ก์ „ํƒ‘์˜ ๊ฐœ์ˆ˜ n, ๊ทธ๋ฆฌ๊ณ  ์ „์„  ์ •๋ณด wires๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.

์ „์„ ๋“ค ์ค‘ ํ•˜๋‚˜๋ฅผ ๋Š์–ด์„œ ์†ก์ „ํƒ‘ ๊ฐœ์ˆ˜๊ฐ€ ๊ฐ€๋Šฅํ•œ ๋น„์Šทํ•˜๋„๋ก ๋‘ ์ „๋ ฅ๋ง์œผ๋กœ ๋‚˜๋ˆ„์—ˆ์„ ๋•Œ, ๋‘ ์ „๋ ฅ๋ง์ด ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ์†ก์ „ํƒ‘ ๊ฐœ์ˆ˜์˜ ์ฐจ์ด(์ ˆ๋Œ€๊ฐ’)๋ฅผ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.

 

์ œํ•œ์‚ฌํ•ญ

n์€ 2 ์ด์ƒ 100 ์ดํ•˜์ธ ์ž์—ฐ์ˆ˜์ž…๋‹ˆ๋‹ค.

wires๋Š” ๊ธธ์ด๊ฐ€ n-1์ธ ์ •์ˆ˜ํ˜• 2์ฐจ์› ๋ฐฐ์—ด์ž…๋‹ˆ๋‹ค.

wires์˜ ๊ฐ ์›์†Œ๋Š” [v1, v2] 2๊ฐœ์˜ ์ž์—ฐ์ˆ˜๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ์œผ๋ฉฐ, ์ด๋Š” ์ „๋ ฅ๋ง์˜ v1๋ฒˆ ์†ก์ „ํƒ‘๊ณผ v2๋ฒˆ ์†ก์ „ํƒ‘์ด ์ „์„ ์œผ๋กœ ์—ฐ๊ฒฐ๋˜์–ด ์žˆ๋‹ค๋Š” ๊ฒƒ์„ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค.

1 ≤ v1 < v2 ≤ n ์ž…๋‹ˆ๋‹ค.

์ „๋ ฅ๋ง ๋„คํŠธ์›Œํฌ๊ฐ€ ํ•˜๋‚˜์˜ ํŠธ๋ฆฌ ํ˜•ํƒœ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ๋Š” ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง€์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

 

ํ’€์ด

1. wire ์ •๋ณด์— ๋”ฐ๋ผ graph ์ธ์ ‘๋ฐฐ์—ด์— ๊ทธ๋ž˜ํ”„ ์—ฐ๊ฒฐ ์ •๋ณด๋ฅผ ์ €์žฅํ•œ๋‹ค

2. wire์„ ํ•˜๋‚˜์”ฉ ๋Œ๋ฉฐ ํ•ด๋‹น ์ „์„ ์„ ๋Š๊ณ , ๋Š์—ˆ์„ ๋•Œ์˜ ํ•œ์ชฝ ๋ง์˜ ์†ก์ „ํƒ‘ ๊ฐฏ์ˆ˜๋ฅผ ๊ตฌํ•œ๋‹ค (feat BFS)

3. ์†ก์ „ํƒ‘ ๊ฐฏ์ˆ˜๊ฐ€ net์ด๋ผ๋ฉด ๋ฐ˜๋Œ€์ชฝ์€ n-net์ด๋ฏ€๋กœ n-2*net์ด ๋‘ ์ „๋ ฅ๋ง์˜ ์†ก์ „ํƒ‘ ๊ฐฏ์ˆ˜ ์ฐจ์ด๋ผ๊ณ  ๋ณผ ์ˆ˜ ์žˆ๋‹ค (๋ฌผ๋ก  ์ ˆ๋Œ€๊ฐ’ ์—ฐ์‚ฐ ํ•„์š”)

 

#include <string>
#include <vector>
#include <queue>
#include <algorithm>
#include <iostream>

using namespace std;

int bfs(int start, vector<vector<bool>>&graph, int&n) {
    int cnt = 1;
    
    vector<bool> visited(n+1, false);
    queue<int> q;
    
    q.push(start);
    visited[start] = true;
    while(!q.empty()) {
        int cur = q.front();
        q.pop();
        for(int i=1; i<=n; i++) {
            if(!visited[i] && graph[cur][i]) {
                visited[i] = true;
                cnt++;
                q.push(i);
            }
        }
    }
    
    return cnt;
}

int solution(int n, vector<vector<int>> wires) {
    int answer = n;
    
    vector<vector<bool>>graph(n+1, vector<bool>(n+1,false));
    vector<bool> visited(n+1, false);
    
    for(vector<int> wire : wires) {
        graph[wire[0]][wire[1]] = true;
        graph[wire[1]][wire[0]] = true;
    }
    
    for(vector<int> wire : wires) {
        int a = wire[0];
        int b = wire[1];
        graph[a][b] = graph[b][a] = false;
        int net = bfs(a, graph, n);
        int diff = n-2*net < 0 ? 2*net-n : n-2*net;
        answer = min(answer, diff);
        graph[a][b] = graph[b][a] = true;
    }
    
    
    return answer;
}
๋ฐ˜์‘ํ˜•