Skip to content

Commit 6508cbc

Browse files
Merge pull request #26 from coolsks/patch-4
IsGraphATree.cpp
2 parents 84480ee + c0f6b63 commit 6508cbc

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

IsGraphATree.cpp

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
2+
//Is the given graph a tree ?
3+
// Two conditions
4+
//1. Should not contain a cycle : no of edges = n-1
5+
//2. 1 connected component
6+
7+
#include <bits/stdc++.h>
8+
using namespace std;
9+
10+
#define ll long long
11+
#define pb push_back
12+
#define mp make_pair
13+
#define ff first
14+
#define ss second
15+
#define f(i, a, n) for (i = a; i < n; i++)
16+
#define fe(i, a, n) for (i = a; i <= n; i++)
17+
#define w(x) \
18+
int x; \
19+
cin >> x; \
20+
while (x--)
21+
#define mod 1000000007
22+
#define ps(x, y) fixed << setprecision(y) << x
23+
24+
void sks()
25+
{
26+
#ifndef ONLINE_JUDGE
27+
freopen("input.txt", "r", stdin);
28+
freopen("output.txt", "w", stdout);
29+
#endif
30+
31+
ios_base::sync_with_stdio(false);
32+
cin.tie(NULL);
33+
cout.tie(NULL);
34+
}
35+
36+
vector<int> adj[10001];
37+
int vis[10001];
38+
39+
void dfs(int node)
40+
{
41+
vis[node] = 1;
42+
43+
for (int child : adj[node])
44+
{
45+
if (!vis[child])
46+
dfs(child);
47+
}
48+
}
49+
50+
int main()
51+
{
52+
sks();
53+
54+
int n, m, a, b, i, cv = 0;
55+
cin >> n >> m;
56+
57+
fe(i, 1, m)
58+
{
59+
cin >> a >> b;
60+
adj[a].pb(b);
61+
adj[b].pb(a);
62+
}
63+
64+
cv = 0;
65+
fe(i, 1, n)
66+
{
67+
if (vis[i] == 0)
68+
{
69+
dfs(i);
70+
cv++;
71+
}
72+
}
73+
74+
if (cv == 1 && m == n - 1)
75+
cout << "YES" << endl;
76+
77+
else
78+
cout << "NO" << endl;
79+
80+
return 0;
81+
}

0 commit comments

Comments
 (0)