题意:
判断一个无向图是不是二分图。
思路:
深搜。
实现:
1 #include <iostream> 2 #include <cstdio> 3 #include <vector> 4 #include <cstring> 5 using namespace std; 6 7 const int MAXN = 2000; 8 vector<int> G[MAXN + 5]; 9 int T, n, m, x, y, color[MAXN + 5]; 10 11 bool dfs(int x, int c) 12 { 13 color[x] = c; 14 for (int i = 0; i < G[x].size(); i++) 15 { 16 int t = G[x][i]; 17 if (color[t] == c) 18 return false; 19 if (color[t] == 0 && !dfs(t, -c)) 20 return false; 21 } 22 return true; 23 } 24 25 int main() 26 { 27 cin >> T; 28 for (int t = 1; t <= T; t++) 29 { 30 cin >> n >> m; 31 for (int i = 1; i <= n; i++) 32 { 33 G[i].clear(); 34 } 35 memset(color, 0, sizeof(color)); 36 for (int i = 0; i < m; i++) 37 { 38 scanf("%d %d", &x, &y); 39 G[x].push_back(y); 40 G[y].push_back(x); 41 } 42 bool flag = true; 43 for (int i = 1; i <= n; i++) 44 { 45 if (!color[i]) 46 { 47 if (!dfs(i, 1)) 48 { 49 flag = false; 50 break; 51 } 52 } 53 } 54 cout << "Scenario " << "#" << t << ":" << endl; 55 if (!flag) 56 { 57 cout << "Suspicious bugs found!" << endl << endl; 58 } 59 else 60 { 61 cout << "No suspicious bugs found!" << endl << endl; 62 } 63 } 64 return 0; 65 }
总结:
还可以使用并查集。