-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathis_tree.cpp
More file actions
47 lines (42 loc) · 860 Bytes
/
is_tree.cpp
File metadata and controls
47 lines (42 loc) · 860 Bytes
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
#include <iostream>
#include <stack>
#include <unordered_map>
#include <vector>
using namespace std;
int dfs(const vector<vector<int>> &g) {
int connected = 1;
vector<bool> visited(g.size(), 0);
stack<int> q;
q.push(0);
visited[0] = true;
while (!q.empty()) {
int t = q.top();
q.pop();
for (auto c : g[t]) {
if (!visited[c]) {
q.push(c);
visited[c] = true;
++connected;
}
}
}
return connected;
}
int main() {
int n, m;
cin >> n >> m;
if (m == n - 1) {
vector<vector<int>> g(n, vector<int>());
for (int i = 0; i < m; ++i) {
int v1, v2;
cin >> v1 >> v2;
// for undirected graph
g[v1 - 1].push_back(v2 - 1);
g[v2 - 1].push_back(v1 - 1);
}
(dfs(g) == n) ? cout << "YES\n" : cout << "NO\n";
} else {
cout << "NO\n";
}
return 0;
}