So I am trying to solve a problem on hackerearth https://www.hackerearth.com/practice/data-structures/trees/binary-and-nary-trees/practice-problems/algorithm/mancunian-and-colored-tree/ where in the editorial stack is being used i am not sure how can i get the element at particular index from stack as far as i know and what is searched on google it says stack has only two operations pop and push for the top most element in stack. Can someone please explain how stack is being used in the editorial code. I have tried all the day but could not figure out how the stack being used.
#include<bits/stdc++.h>
using namespace std;
#define SIZE 100005
vector<int> adj[SIZE];
int ans[SIZE],col[SIZE];
int n,c;
stack<int> st[SIZE];
void dfs(int v)
{
if(st[col[v]].empty()){
ans[v]=-1;
}
else
{
ans[v]=st[col[v]].top();
}
st[col[v]].push(v);
for(int i=0;i<(int)adj[v].size();++i){
int vv = adj[v][i];
dfs(vv);
}
st[col[v]].pop();
}
int main()
{
cin>>n>>c;
for(int i=2;i<=n;i++)
{
int p;
cin>>p;
adj[p].push_back(i);
}
for(int i=1;i<=n;i++)
cin>>col[i];
dfs(1);
for(int i=1;i<=n;i++)
cout<<ans[i]<<" " ;
return 0;
}
Aucun commentaire:
Enregistrer un commentaire