Time Limit: 2 sec / Memory Limit: 1024 MB
Score : 300300 points
Problem Statement
There is a tree TT with NN vertices. The ii-th edge (1\leq i\leq N-1)(1≤i≤N−1) connects vertex U_iUi and vertex V_iVi.
You are given two different vertices XX and YY in TT. List all vertices along the simple path from vertex XX to vertex YY in order, including endpoints.
It can be proved that, for any two different vertices aa and bb in a tree, there is a unique simple path from aa to bb.
What is a simple path?
Constraints
- 1\leq N\leq 2\times 10^51≤N≤2×105
- 1\leq X,Y\leq N1≤X,Y≤N
- X\neq YX=Y
- 1\leq U_i,V_i\leq N1≤Ui,Vi≤N
- All values in the input are integers.
- The given graph is a tree.
Input
The input is given from Standard Input in the following format:
NN XX YY U_1U1 V_1V1 U_2U2 V_2V2 \vdots⋮ U_{N-1}UN−1 V_{N-1}VN−1
Output
Print the indices of all vertices along the simple path from vertex XX to vertex YY in order, with spaces in between.
Sample Input 1 Copy
Copy
5 2 5 1 2 1 3 3 4 3 5
Sample Output 1 Copy
Copy
2 1 3 5
The tree TT is shown below. The simple path from vertex 22 to vertex 55 is 22 \to→ 11 \to→ 33 \to→ 55.
Thus, 2,1,3,52,1,3,5 should be printed in this order, with spaces in between.
Sample Input 2 Copy
Copy
6 1 2 3 1 2 5 1 2 4 1 2 6
Sample Output 2 Copy
Copy
1 2
The tree TT is shown below.
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
const int N=200005;
struct e
{
vector<int> vt;
} eg[N];
int n,x,y,sum=1;
bool vis[N];
int ans[N];
void dfs(int u)
{
int res=1;
ans[sum]=u;
if(u==y)
{
for(int i=1;i<=sum;i++)
{
cout<<ans[i]<<" ";
}
return;
}
for(vector<int>::iterator it=eg[u].vt.begin();it!=eg[u].vt.end();it++)
{
int v=*it;
if(!vis[v])
{
sum+=res;
vis[v]=true;
dfs(v);
vis[v]=false;
sum--;
}
}
return;
}
int main()
{
memset(vis,false,sizeof(vis));
int u,v;
cin>>n>>x>>y;
n--;
while(n--)
{
cin>>u>>v;
eg[u].vt.push_back(v);
eg[v].vt.push_back(u);
}
vis[x]=true;
dfs(x);
return 0;
}