九度oj 1109

来源:互联网 发布:windowsvps搭建数据库 编辑:程序博客网 时间:2024/06/12 00:05
题目描述:

    给定一个无向图和其中的所有边,判断这个图是否所有顶点都是连通的。

输入:

    每组数据的第一行是两个整数 n 和 m(0<=n<=1000)。n 表示图的顶点数目,m 表示图中边的数目。如果 n 为 0 表示输入结束。随后有 m 行数据,每行有两个值 x 和 y(0<x, y <=n),表示顶点 x 和 y 相连,顶点的编号从 1 开始计算。输入不保证这些边是否重复。

输出:

    对于每组输入数据,如果所有顶点都是连通的,输出"YES",否则输出"NO"。

样例输入:
4 31 22 33 23 21 2
2 30 0
样例输出:
NOYES
来源:
  1. 2011年吉林大学计算机研究生机试真题
#include<iostream>#include<string.h>using namespace std;#define N 2000int tree[N];int findroot(int x){    if(tree[x]==-1)    return x;    else    return findroot(tree[x]);}    int main(){    int n,m,p1,p2;    while(cin>>n>>m)    {                    if(n==0)                    {                            break;                            }                    memset(tree,-1,sizeof(tree));                    while(m--!=0)                    {                        cin>>p1>>p2;                                              int a=findroot(p1);                        int b=findroot(p2);                        if(a!=b)                        {                                tree[a]=b;                                }                                }                                int ans=0;                                for(int i=1;i<=n&&ans<2;i++)                                {                                        if(tree[i]==-1)                                        {                                                       ans++;                                                       }                                                       }                                                       if(ans==1)                                                       {                                                                 cout<<"YES"<<endl;                                                                 }                                                                 else                                                                 cout<<"NO"<<endl;                                                                 }                                                                 }                                  


0 0