๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค(Programmers)

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

by dkswnkk 2022. 4. 18.

๋ฌธ์ œ

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์ „๋ ฅ๋ง์„ ๋‘˜๋กœ ๋‚˜๋ˆ„๊ธฐ

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 <memory.h>

using namespace std;

vector<int>graph[101];
vector<pair<int,int>>divide;
bool visited[101];
int group_cnt;
int node_cnt[2];

void dfs(int node, pair<int,int> cut){
    visited[node] = 1;
    node_cnt[group_cnt]++;
    for(int i=0; i<graph[node].size(); i++){
        int next = graph[node][i];
        if((node==cut.first&&next==cut.second)||(node==cut.second&&next==cut.first)) continue;
        if(visited[next]) continue;
        dfs(next, cut);
    }
}
int solution(int n, vector<vector<int>> wires) {
    int answer = 1e9;
    
    for(int i=0; i<wires.size(); i++){
        int a = wires[i][0];
        int b = wires[i][1];
        graph[a].push_back(b);
        graph[b].push_back(a);
        divide.push_back({a,b});
    }
    
    for(int i=0; i<divide.size(); i++){
        int a = divide[i].first;
        int b = divide[i].second;
        
        for(int k=1; k<=wires.size(); k++){
            if(visited[k]) continue;
            dfs(k, {a,b});
            group_cnt++;
        }
        
        if(group_cnt==2) answer = min(answer, abs(node_cnt[0]-node_cnt[1]));   //๋‘๊ฐœ๋กœ ๋ถ„ํ•  ๋˜์—ˆ์„ ๋•Œ
        group_cnt = 0;
        memset(visited, 0, sizeof(visited));
        node_cnt[0] = 0, node_cnt[1] = 0;
    }

 

ํ’€์ด

ํ•˜๋‚˜์”ฉ ์ „์„ ์„ ๋Š์–ด๊ฐ€๋ฉฐ ๋ชจ๋“  ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ํƒ์ƒ‰ํ•˜์˜€์Šต๋‹ˆ๋‹ค. ๋Š์„ ๋…ธ๋“œ ๋‘ ๊ฐœ๋ฅผ pair๋ฅผ ํ†ตํ•ด์„œ ์ธ์ž ๊ฐ’์œผ๋กœ ๋„˜๊ธฐ๊ณ  ์•„๋ž˜ ์ฝ”๋“œ๋ฅผ ํ†ตํ•ด ๋Š๊ธด ๋ถ€๋ถ„์ด๋ผ๋ฉด ํƒ์ƒ‰ํ•˜์ง€ ์•Š๋Š” ๋ฐฉ์‹์œผ๋กœ ๊ตฌํ˜„ํ–ˆ์Šต๋‹ˆ๋‹ค.

if((node==cut.first&&next==cut.second)||(node==cut.second&&next==cut.first))

 

์ตœ์ข…์ ์œผ๋กœ group_cnt๊ฐ€ ๋‘๊ฐœ๊ฐ€ ๋˜๋ฉด ๋‘ ์ „๋ ฅ๋ง์œผ๋กœ ๋‚˜๋ˆ„์–ด์ง„ ๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ์—  ์•„๋ž˜ ์ฝ”๋“œ๋ฅผ ํ†ตํ•ด ์ตœ๋Œ€ํ•œ ๊ท ๋“ฑํ•˜๊ฒŒ ๋‚˜๋‰˜์–ด์ง„ ๊ฐ’์„ ๊ฐฑ์‹ ํ•˜๋ฉด์„œ ๋ชจ๋“  ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ํƒ์ƒ‰ํ–ˆ์Šต๋‹ˆ๋‹ค.

 if(group_cnt==2) answer = min(answer, abs(node_cnt[0]-node_cnt[1]));   //๋‘๊ฐœ๋กœ ๋ถ„ํ•  ๋˜์—ˆ์„ ๋•Œ

 

๋Œ“๊ธ€