1. 程式人生 > >NYOJ - 1015 二部圖(bfs/dfs)

NYOJ - 1015 二部圖(bfs/dfs)

for esp 題意 const ring cto style ios line

題目鏈接:點我點我

題意:二分圖判斷問題

題解:兩種解法,模擬下匹配過程。

 1 //二分圖匹配dfs
 2 #include <cstring>
 3 #include <vector>
 4 #include <iostream>
 5 #include <algorithm>
 6 using namespace std;
 7 
 8 const int N=11111;
 9 vector <int> E[N];
10 int col[N];
11 
12 void init(){
13     memset(col,0
,sizeof(col)); 14 for(int i=0;i<N;i++) E[i].clear(); 15 } 16 17 bool dfs(int v,int c){ 18 col[v]=c; 19 for(int i=0;i<E[v].size();i++){ 20 int tmp=E[v][i]; 21 if(col[tmp]==c) return false; 22 if(col[tmp]==0&&!dfs(tmp,-c)) return false; 23 }
24 return true; 25 } 26 27 int main(){ 28 int n,m,x,y; 29 while(cin>>n){ 30 int idx=0; 31 init(); 32 cin>>m; 33 for(int i=1;i<=m;i++){ 34 cin>>x>>y; 35 E[x].push_back(y); 36 E[y].push_back(x);
37 } 38 if(!dfs(0,1)) cout<<"NOT BICOLORABLE."<<endl; 39 else cout<<"BICOLORABLE."<<endl; 40 } 41 return 0; 42 }
 1 //二分圖匹配bfs 
 2 #include <queue>
 3 #include <cstring>
 4 #include <vector>
 5 #include <iostream>
 6 #include <algorithm>
 7 using namespace std;
 8 
 9 const int N=11111;
10 vector <int> E[N];
11 int col[N];
12 
13 void init(){
14     memset(col,0,sizeof(col));
15     for(int i=0;i<N;i++) E[i].clear();            
16 }
17 
18 bool bfs(int x){
19     col[x]=1;
20     queue <int> Q;
21     Q.push(x);
22     while(!Q.empty()){
23         int now=Q.front();Q.pop();
24         for(int i=0;i<E[now].size();i++){
25             int tmp=E[now][i];
26             int ctmp=col[now]==1?2:1;
27             if(col[tmp]==0){
28                 col[tmp]=ctmp;
29                 Q.push(tmp);
30             }
31             else if(col[tmp]!=ctmp) return false;
32         }    
33     }
34     return true;
35 }
36 
37 int main(){
38     int n,m;
39     while(cin>>n){
40         init();
41         int x,y;
42         cin>>m;
43         for(int i=1;i<=m;i++){
44             cin>>x>>y;
45             E[x].push_back(y);
46             E[y].push_back(x);
47         }
48         if(bfs(0)) cout<<"BICOLORABLE."<<endl;
49         else cout<<"NOT BICOLORABLE."<<endl;
50     }    
51     return 0;
52 }        

NYOJ - 1015 二部圖(bfs/dfs)