SPOJ1436(Is it a tree)

1436. Is it a tree

Problem code: PT07Y

You are given an unweighted, undirected graph. Write a program to check if it's a tree topology.

Input

The first line of the input file contains two integers N and M --- number of nodes and number of edges in the graph (0 < N <= 10000, 0 <= M <= 20000). Next M lines contain M edges of that graph --- Each line contains a pair (u, v) means there is an edge between node u and node v (1 <= u,v <= N).

Output

Print YES if the given graph is a tree, otherwise print NO.

Example

Input:
3 2
1 2
2 3
Output:
YES
//2009-05-17 12:22:31     Xredman    Is it a tree    accepted     0.10      2.9M      C++ 
#include <iostream>
#include 
<vector>
using namespace std;

const int N = 10005;

bool Visited[N];
vector
<int> V[N];
int n, m;
int cnt;

void init()
ExpandedBlockStart.gifContractedBlock.gif
{
    
for(int i = 1; i <= n; i++)
        V[i].clear();
}



void dfs(int cc)
ExpandedBlockStart.gifContractedBlock.gif
{
    vector
<int>::iterator p;
    p 
= V[cc].begin();
    
    
while(p != V[cc].end())
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
if(!Visited[*p])
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            Visited[
*p] = true;
            cnt
++;
            dfs(
*p);
        }

        p
++;
    }

}


int main()
ExpandedBlockStart.gifContractedBlock.gif
{
    
int u, v, k;
    
while(scanf("%d%d"&n, &m) != EOF)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        

        init();
        
for(k = 0; k < m; k++)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            scanf(
"%d%d"&u, &v);

            V[u].push_back(v);
            V[v].push_back(u);
        }

        
if(n == 1)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            printf(
"YES\n");
            
continue;
        }

        
if(m != n -1)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            printf(
"NO\n");
            
continue;
        }

        memset(Visited, 
falsesizeof(Visited));
        Visited[
1= true;
        cnt 
= 1;
        dfs(
1);

        
if(cnt == n)
            printf(
"YES\n");
        
else
            printf(
"NO\n");
    }

    
return 0;
}

转载于:https://www.cnblogs.com/Xredman/archive/2009/05/17/1458896.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值