๋ฌธ์
์ฝ๋
#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])); //๋๊ฐ๋ก ๋ถํ ๋์์ ๋
'Algorithm ๐ง๐ปโ๐ป > ํ๋ก๊ทธ๋๋จธ์ค(Programmers)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[c++] ํ๋ก๊ทธ๋๋จธ์ค - ์ซ์์ ํํ(Level 2) (0) | 2022.04.24 |
---|---|
[c++] ํ๋ก๊ทธ๋๋จธ์ค - ํฐ ์ ๋ง๋ค๊ธฐ(Level 2) (0) | 2022.04.24 |
[c++] ํ๋ก๊ทธ๋๋จธ์ค - ๊ดํธ ํ์ ํ๊ธฐ(Level 2) (0) | 2022.04.19 |
[c++] ํ๋ก๊ทธ๋๋จธ์ค - ๋ค์ ํฐ ์ซ์(Level 2) (0) | 2022.04.18 |
[c++] ํ๋ก๊ทธ๋๋จธ์ค - ์ฌ๋ฐ๋ฅธ ๊ดํธ(Level 2) (0) | 2022.04.18 |
[c++] ํ๋ก๊ทธ๋๋จธ์ค - ๋ ๋ฐ๋จน๊ธฐ(Level 2) (2) | 2022.04.18 |
๋๊ธ