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 nodesV1, V2,V3, ... Vk, such that there are edges betweenV1 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 nodex 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
题目大意:给你n个结点m条边组成无向图,求该无向图是不是一个环,是输出“YES”, 否输出“NO”;
分析:记录每个节点的度【如果能是环,则每个节点的度均为2】,然后在判断是否左右结点都在这个图中;
可以在输入边时记录该边连接的两个结点的度,判断所有点是否在一个图中,可以用并查集~~~
已Accept代码【c++】
#include <cstdio>
#include <cstring>
using namespace std;
int n, m;
int pre[11], map[11];
int Find(int x) {
int r = x;
while(r != pre[r])
r = pre[r];
int i = x, j;
while(i != r) {
j = pre[i];
pre[i] = r;
i = j;
}
return r;
}
void Join(int x, int y) {
int fx = Find(x);
int fy = Find(y);
if(fx != fy)
pre[fx] = fy;
}
bool Ok() {
for(int i = 1; i <= n; i++)
if(map[i] != 2)
return false;
int ok = Find(1);
for(int i = 2; i <= n; i++)
if(ok != Find(i))
return false;
return true;
}
int main() {
int a, b;
while(scanf("%d%d", &n, &m) != EOF) {
for(int i = 1; i <= n; i++) {
pre[i] = i;
map[i] = 0;
}
for(int i = 0; i < m; i++) {
scanf("%d %d", &a, &b);
Join(a, b);
map[a]++;
map[b]++;
}
printf("%s\n", Ok() ? "YES" : "NO");
}
return 0;
}