题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=3731
Your task is so easy. I will give you an undirected graph, and you just need to tell me whether the graph is just a circle. A cycle is three or more nodes V1, V2, V3, ...Vk, such that there are edges between V1 and V2, V2 and V3, ... Vk and V1, with no other extra edges. The graph will not contain self-loop. Furthermore, there is at most one edge between two nodes.
Input
There are multiple cases (no more than 10).
The first line contains two integers n and m, which indicate the number of nodes and the number of edges (1 < n < 10, 1 <= m < 20).
Following are m lines, each contains two integers x and y (1 <= x, y <= n, x != y), which means there is an edge between node x and node y.
There is a blank line between cases.
Output
If the graph is just a circle, output "YES", otherwise output "NO".
Sample Input
3 3 1 2 2 3 1 3 4 4 1 2 2 3 3 1 1 4
Sample Output
YES NO
题意:
求所给的所有边能恰好形成一个圆!
代码一:
#include <cstdio> #include <cstring> int f[147]; int ma[147]; int find(int x) { return x==f[x] ? x:f[x]=find(f[x]); } void init(int n) { for(int i = 0; i <= n; i++) { f[i] = i; } } void Union(int x, int y) { int f1 = find(x); int f2 = find(y); if(f1 != f2) { f[f2] = f1; } } int main() { int n, m; while(~scanf("%d%d",&n,&m)) { memset(ma, 0,sizeof(ma)); int a, b; init(n); for(int i = 0; i < m; i++) { scanf("%d%d",&a,&b); Union(a,b); ma[a]++, ma[b]++; } int flag = 0; for(int i = 1; i <= n; i++) { if(ma[i] != 2)//每个点只能出现两次 { flag = 1; break; } if(f[i] != f[n]) { flag = 1; break; } } if(flag) { printf("NO\n"); } else { printf("YES\n"); } } return 0; }
#include <cstdio> #include <cstring> int main() { int n, m; int map[25][25]; while(scanf("%d%d", &n, &m)!=EOF) { int a, b; memset(map, 0, sizeof(map)); for(int i = 0; i < m; i++) { scanf("%d%d", &a, &b); map[a][b] = map[b][a] = 1; } if(n != m) { printf("NO\n"); continue; } int ans = 0; int flag = 0; int tt = 1; for(int i = 1; i <= m; i++) { flag = 0; for(int j = 1; j <= n; j++)//从点1开始循环,如果最后可以回到点1,就说明是一个圆 if(map[tt][j]) { map[tt][j] = map[j][tt] = 0;//标记已找到的边 tt = j; flag = 1; break; } if(flag == 0)//没找到 { ans = -1; break; } } if(tt != 1) ans = -1; if(ans == 0) printf("YES\n"); if(ans == -1) printf("NO\n"); } return 0; }
原文地址:http://blog.csdn.net/u012860063/article/details/44876785