Actually you wrote correct sequence but in reverse order and skipping the first(last) element
You may change the last for to include the first element
vector<int> v;
for(int k=end;k!=-1;k=b[k])
{
cout << a[k] << ' ';
}
You may need to store element in something like std::vector
to reverse it to get correct order
vector<int> v;
for(int k=end;k!=-1;k=b[k])
{
v.push_back(a[k]);
}
reverse(v.begin(), v.end());
for(int x: v) {
cout << x << ' ';
}