BOJ 1707
์ด๋ถ ๊ทธ๋ํ ์ฑ๊ณต
2 ์ด 256 MB 69417 18251 10951 23.507% ๋ฌธ์
๊ทธ๋ํ์ ์ ์ ์ ์งํฉ์ ๋๋ก ๋ถํ ํ์ฌ, ๊ฐ ์งํฉ์ ์ํ ์ ์ ๋ผ๋ฆฌ๋ ์๋ก ์ธ์ ํ์ง ์๋๋ก ๋ถํ ํ ์ ์์ ๋, ๊ทธ๋ฌํ ๊ทธ๋ํ๋ฅผ ํน๋ณํ ์ด๋ถ ๊ทธ๋ํ (Bipartite Graph) ๋ผ ๋ถ๋ฅธ๋ค.
๊ทธ๋ํ๊ฐ ์ ๋ ฅ์ผ๋ก ์ฃผ์ด์ก์ ๋, ์ด ๊ทธ๋ํ๊ฐ ์ด๋ถ ๊ทธ๋ํ์ธ์ง ์๋์ง ํ๋ณํ๋ ํ๋ก๊ทธ๋จ์ ์์ฑํ์์ค.
์ ๋ ฅ
์ ๋ ฅ์ ์ฌ๋ฌ ๊ฐ์ ํ ์คํธ ์ผ์ด์ค๋ก ๊ตฌ์ฑ๋์ด ์๋๋ฐ, ์ฒซ์งธ ์ค์ ํ ์คํธ ์ผ์ด์ค์ ๊ฐ์ K๊ฐ ์ฃผ์ด์ง๋ค. ๊ฐ ํ ์คํธ ์ผ์ด์ค์ ์ฒซ์งธ ์ค์๋ ๊ทธ๋ํ์ ์ ์ ์ ๊ฐ์ V์ ๊ฐ์ ์ ๊ฐ์ E๊ฐ ๋น ์นธ์ ์ฌ์ด์ ๋๊ณ ์์๋๋ก ์ฃผ์ด์ง๋ค. ๊ฐ ์ ์ ์๋ 1๋ถํฐ V๊น์ง ์ฐจ๋ก๋ก ๋ฒํธ๊ฐ ๋ถ์ด ์๋ค. ์ด์ด์ ๋์งธ ์ค๋ถํฐ E๊ฐ์ ์ค์ ๊ฑธ์ณ ๊ฐ์ ์ ๋ํ ์ ๋ณด๊ฐ ์ฃผ์ด์ง๋๋ฐ, ๊ฐ ์ค์ ์ธ์ ํ ๋ ์ ์ ์ ๋ฒํธ u, v (u ≠ v)๊ฐ ๋น ์นธ์ ์ฌ์ด์ ๋๊ณ ์ฃผ์ด์ง๋ค.
์ถ๋ ฅ
K๊ฐ์ ์ค์ ๊ฑธ์ณ ์ ๋ ฅ์ผ๋ก ์ฃผ์ด์ง ๊ทธ๋ํ๊ฐ ์ด๋ถ ๊ทธ๋ํ์ด๋ฉด YES, ์๋๋ฉด NO๋ฅผ ์์๋๋ก ์ถ๋ ฅํ๋ค.
์ ํ
- 2 ≤ K ≤ 5
- 1 ≤ V ≤ 20,000
- 1 ≤ E ≤ 200,000
์์ ์ ๋ ฅ 1 ๋ณต์ฌ
2 3 2 1 3 2 3 4 4 1 2 2 3 3 4 4 2
์์ ์ถ๋ ฅ 1 ๋ณต์ฌ
YES NOโ
BFS๋ DFS๋ก brute-force๋ฅผ ํด์ ๊ฐ ๋ ธ๋์ ์ด์ ๋ ธ๋์ ๋ค๋ฅธ ์๊น(0 or 1)์ ๋ฃ์ด์ค ๋ค์
๋ง์ฝ ๊ทธ๋ํ์ ๊ฐ์ ์ด ๊ฐ์ ์์ ๋ ธ๋๋ฅผ ๊ฐ๋ฆฌํค๋ฉด, ์ด๋ถ ๊ทธ๋ํ๊ฐ ๋ ์ ์๋ค๋ ๊ฒ์ ์ด์ฉํ๋ฉด ๋๋ค.
๋ฌธ์ ์ ์กฐ๊ฑด์ ์ ๋๋ก ๋ณด์ง ๋ชปํ๊ณ ๋น์ฐํ ๋ ธ๋๋ผ๋ฆฌ ๋ค ์ฐ๊ฒฐ๋์ด์๋์ค ์์์ ์์์ ์ 1๋ก ๋ฃ๊ณ ๋๋ ธ๋๋ฐ, ๊ณ์ํ๋ ค์ ๋ชจ๋ ๋ ธ๋์ ๋ํ ํ์์ ๋ค ๋๋ฆฌ๋๊น ๋ง์๋ค. ์ฐ๊ฒฐ๋์ง ์๋ ๊ฒฝ์ฐ๋ ์๊ฐํด์ผ ๋๋ค.
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
int K, V, E;
int main(){
cin>>K;
while(K--){
vector<vector<int>>graph(20001);
bool color[20001]={0};
int vis[20001] = {0};
cin>>V>>E;
for(int i=0; i<E; i++){
int a, b;
cin>>a>>b;
graph[a].push_back(b);
graph[b].push_back(a);
}
// int cur = 1, quit = 0;
// color[cur] = 0;
// vis[cur] = 1;
// //0 -> black, 1 -> red
// queue<pair<int,int>>q;
// //first -> node, second -> color
// q.push({cur, 0});
int quit = 0;
for(int i=1; i<=V; i++){
if(vis[i]) continue;
color[i] = 0;
vis[i] = 1;
queue<pair<int,int>>q;
q.push({i,0});
while(!q.empty()){
auto cur_node = q.front().first;
auto cur_color = q.front().second;
q.pop();
for(auto edge : graph[cur_node]){
if(vis[edge]){
if(color[edge] == cur_color){
//end
quit = 1;
break;
}
continue;
}
vis[edge] = 1;
color[edge] = !cur_color;
q.push({edge,!cur_color});
}
if(quit) break;
}
if(quit) break;
}
if(!quit){
for(int i=1; i<=V; i++)
for(auto edge : graph[i]){
if(color[i] == color[edge]) quit=1;
}
}
if(!quit)
cout<<"YES\n";
else
cout<<"NO\n";
}
}