zoj 3321 Circle【並查集】
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
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
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;
}