首页 > 代码库 > 图论trainning-part-1 B. Claw Decomposition
图论trainning-part-1 B. Claw Decomposition
B. Claw Decomposition
A claw is defined as a pointed curved nail on the end of each toe in birds, some reptiles, and some mammals. However, if you are a graph theory enthusiast, you may understand the following special class of graph as shown in the following figure by the word claw.
If you are more concerned about graph theory terminology, you may want to define claw as K1,3.
Lets leave the definition for the moment & come to the problem. You are given a simple undirected graph in which every vertex has degree 3. You are to figure out whether the graph can be decomposed into claws or not.
Just for the sake of clarity, a decomposition of a graph is a list of subgraphs such that each edge appears in exactly one subgraph in the list.
Input
There will be several cases in the input file. Each case starts with the number of vertices in the graph, V (4<=V<=300). This is followed by a list of edges. Every line in the list has two integers, a & b, the endpoints of an edge (1<=a,b<=V). The edge list ends with a line with a pair of 0. The end of input is denoted by a case with V=0. This case should not be processed.
Output
For every case in the input, print YES if the graph can be decomposed into claws & NO otherwise.
Sample Input Output for Sample Input
4 1 2 1 3 1 4 2 3 2 4 3 4 0 0 6 1 2 1 3 1 6 2 3 2 5 3 4 4 5 4 6 5 6 0 0 0 | NO NO |
Problemsetter: Mohammad Mahmudur Rahman
Special Thanks to: Manzurur Rahman Khan
解题:二分图的判断,使用染色法!如果相邻顶点颜色相同,即不是二分图。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cmath> 5 #include <algorithm> 6 #include <climits> 7 #include <vector> 8 #include <queue> 9 #include <cstdlib>10 #include <string>11 #include <set>12 #define LL long long13 #define INF 0x3f3f3f3f14 using namespace std;15 const int maxv = 310;16 struct arc{17 int v;18 };19 vector<arc>g[maxv];20 int n;21 bool color[maxv];22 bool dfs(int u){23 for(int i = 0; i < g[u].size(); i++){24 int j = g[u][i].v;25 if(!color[j]){26 color[j] = !color[u];27 if(!dfs(j)) return false;28 }else if(color[j] == color[u]) return false;29 }30 return true;31 }32 int main() {33 int i,u,v;34 while(scanf("%d",&n),n){35 if(n == 1) {puts("NO");continue;}36 for(i = 1; i <= n; i++)37 g[i].clear();38 while(scanf("%d%d",&u,&v),u||v){39 g[u].push_back((arc){v});40 g[v].push_back((arc){u});41 }42 memset(color,false,sizeof(color));43 dfs(1)?puts("YES"):puts("NO");44 }45 return 0;46 }