-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiterative dfs.cpp
More file actions
55 lines (48 loc) · 1.16 KB
/
Copy pathiterative dfs.cpp
File metadata and controls
55 lines (48 loc) · 1.16 KB
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
#include<bits/stdc++.h>
using namespace std;
#define pii pair<int,int>
#define sz 100009
vector<int>v[sz];
int par[sz],st[sz],en[sz],tim=0;
void dfs(int n,int parent)
{
stack<pii >sk;
sk.push(make_pair(n,0));
st[n]=++tim;
par[n]=parent; ///par[n] holds parent for n node
while(!sk.empty())
{
pii x=sk.top();
sk.pop();
if(x.second==v[x.first].size())
{
en[x.first]=++tim;/// all children are taken
continue;
}
if(v[x.first][x.second]==par[x.first])
{
sk.push(make_pair(x.first,x.second+1));/// ignoring parent
}
else
{
sk.push(make_pair(x.first,x.second+1));
sk.push(make_pair(v[x.first][x.second],0)); ///new child
st[v[x.first][x.second]]=++tim;
par[v[x.first][x.second]]=x.first;
}
}
}
int main()
{
int n,a,b,i;
scanf("%d",&n);
for(i=1;i<n;i++)
{
scanf("%d %d",&a,&b);
v[a].push_back(b);
v[b].push_back(a);
}
dfs(1,1);///root pass
for(i=1;i<=n;i++)
cout<<st[i]<<" "<<en[i]<<"\n";
}