SPOJ1436(Is it a tree)
1436. Is it a treeProblem 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()
{
for(int i = 1; i <= n; i++)
V[i].clear();
}
void dfs(int cc)
{
vector<int>::iterator p;
p = V[cc].begin();
while(p != V[cc].end())
{
if(!Visited[*p])
{
Visited[*p] = true;
cnt++;
dfs(*p);
}
p++;
}
}
int main()
{
int u, v, k;
while(scanf("%d%d", &n, &m) != EOF)
{
init();
for(k = 0; k < m; k++)
{
scanf("%d%d", &u, &v);
V[u].push_back(v);
V[v].push_back(u);
}
if(n == 1)
{
printf("YES\n");
continue;
}
if(m != n -1)
{
printf("NO\n");
continue;
}
memset(Visited, false, sizeof(Visited));
Visited[1] = true;
cnt = 1;
dfs(1);
if(cnt == n)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}
#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()
{
for(int i = 1; i <= n; i++)
V[i].clear();
}
void dfs(int cc)
{
vector<int>::iterator p;
p = V[cc].begin();
while(p != V[cc].end())
{
if(!Visited[*p])
{
Visited[*p] = true;
cnt++;
dfs(*p);
}
p++;
}
}
int main()
{
int u, v, k;
while(scanf("%d%d", &n, &m) != EOF)
{
init();
for(k = 0; k < m; k++)
{
scanf("%d%d", &u, &v);
V[u].push_back(v);
V[v].push_back(u);
}
if(n == 1)
{
printf("YES\n");
continue;
}
if(m != n -1)
{
printf("NO\n");
continue;
}
memset(Visited, false, sizeof(Visited));
Visited[1] = true;
cnt = 1;
dfs(1);
if(cnt == n)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}