无向图的联通分量NEUACM1134: Searching for TwoBee

来源:互联网 发布:激光美容知乎 编辑:程序博客网 时间:2024/04/29 17:39

题目链接:http://acm.neu.edu.cn/hustoj/problem.php?id=1134

题目描述

Zhuo deeply loves TwoBee. But one day TwoBee got lost, Zhuo got crazy searching for TwoBee all over the world. Now give you a map that contains the places that Zhuo and the lost TwoBee may be in. there are N places and M bidirectional roads in the map. Zhuo and TwoBee stay at a random place initially, and TwoBee is too scared to move any more. Does it possible for Zhuo to find TwoBee no matter where the places they stay initially?

输入

This problem contains multiple test cases. The first row contains two integers N, M (1<=N<=1000,0<=M<=10000)which has been mentioned above. In the next M lines, each line contains two integers a,b(1<=a,b<=N),which indicates there is a road between a and b.

输出

Print exactly one line with a string “YES” if Zhuo is possible to find TwoBee, otherwise output a string “NO”.  


显然这题是求无向图的联通分量,如果只有一个,那么所有点可以互达,输出yes,否则输出no。求一个无向图的联通分量可以用DFS在线性时间内求出,如下代码:

void find_cc(){      current_cc=0;      memset(vis,false,sizeof(vis));      for(int u=0;u<n;u++)        if(!vis[u])        {               current_cc++;               dfs(u);        }}

然而如果只需求联通分量,则可以使用并查集,不仅不会出现DFS栈溢出,而且连图都不用保存。

#include <iostream>#include <cstdio>#define MAXN 1050using namespace std; int pa[MAXN]; int findset(int x){     return pa[x]!=x?pa[x]=findset(pa[x]):x;} int main(){    int n,m,x,y;    while(scanf("%d%d",&n,&m)!=EOF)    {          for(int i=1;i<=n;i++)   pa[i]=i;          int num=n;          for(int i=0;i<m;i++)          {                  scanf("%d%d",&x,&y);                  x=findset(x),y=findset(y);                  if(x!=y)                  {                         pa[x]=y;                         num--;                  }          }          if(num==1)             printf("YES\n");           else            printf("NO\n");    }    return 0;} /**************************************************************    Problem: 1134    Language: C++    Result: 正确    Time:18 ms    Memory:1272 kb****************************************************************/


0 0
原创粉丝点击