-
Notifications
You must be signed in to change notification settings - Fork 0
/
Graph_Check_Tree.cpp
72 lines (64 loc) · 1.11 KB
/
Graph_Check_Tree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <bits/stdc++.h>
using namespace std;
int n, E;
vector<vector<int> > adjacent;
vector<int> vertex;
bool visited[10];
void DFS(int s)
{
stack<int> st;
st.push(s);
visited[s] = true;
while(!st.empty())
{
int t = st.top();
st.pop();
for(auto v : adjacent[t])
{
if(!visited[v])
{
visited[v] = true;
st.push(t);
st.push(v);
break;
}
}
}
}
bool isConnected()
{
DFS(0);
for(int i=0; i < n; i++)
{
if(!visited[i])
{
return false;
}
}
return true;
}
bool isTree()
{
return isConnected() and E == n - 1;
}
int main()
{
int u, v;
cin >> n;
for(int i =0; i < n; i++)
{
adjacent.push_back(vertex);
visited[i] = false;
}
for(int i = 0; i < n-1; i++)
{
cin >> u >> v;
E++;
adjacent[u-1].push_back(v-1);
adjacent[v-1].push_back(u-1);
}
if(isTree())
{
cout << "YES" << endl;
} else cout << "NO" << endl;
}