首页 > 代码库 > ZOJ Problem Set - 3321 并查集

ZOJ Problem Set - 3321 并查集

题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3321

 

Circle

Time Limit: 1 Second      Memory Limit: 32768 KB

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 V1V2V3, ... Vk, such that there are edges between V1 and V2V2 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 <= xy <= nx != 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 31 22 31 34 41 22 33 11 4

Sample Output

YESNO




改了队友的经典并查集代码过了此题,记录下作为经典模板使用
#include<iostream>using namespace std;int pre[1010];int find(int x){    return pre[x]==x?x:pre[x]=find(pre[x]);}int main(){    int road,root1,root2,num,i,start,end,total;    while(cin>>num>>road )    {        int sum=0;        total=num-1;        for(i=1; i<=num; i++)            pre[i]=i;        while(road--)        {            cin>>start>>end;            sum+=(start+end);            root1=find(start);            root2=find(end);            if(root1!=root2)            {                pre[root1]=root2;                total--;            }        }        int tmp=0;        for(i=1;i<=num;i++)        {            tmp+=i;        }        if(!total && tmp*2 == sum)        {            cout<<"YES"<<endl;        }        else        {            cout<<"NO"<<endl;        }    }    return 0;}