#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
#include <sstream>
#include <stack>
#include <map>
#include <ctime>
#include <array>
#include <set>
#include <list>
using namespace std;
struct ArcNode
{
int adj;
ArcNode *nextarc;
};
struct vNode
{
string data;
ArcNode *firstarc;
};
struct Node
{
struct vNode arr[100];
int length;
};
struct node
{
string data;
int parent;
};
void create(struct Node &T, vector<node> v, int len)
{
T.length = len;
for (int i = 0; i < len; i++)
{
T.arr[i].data = v[i].data;
T.arr[i].firstarc = NULL;
}
for (int i = len - 1; i >= 0; i--)
{
ArcNode *p = new ArcNode;
p->adj = i;
p->nextarc = T.arr[v[i].parent].firstarc;
T.arr[v[i].parent].firstarc = p;
}
}
int find_num(struct Node T, int u, int v)
{
if (u < 0 || u > T.length)
return -1;
ArcNode *p;
p = T.arr[u].firstarc;
while (p != NULL)
{
if (p->adj == v)
{
if (p->nextarc == NULL)
return -1;
else
return p->nextarc->adj;
}
p = p->nextarc;
}
return -1;
}
int visit[100] = {0};
void preDFS(struct Node T, int v)
{
if (v == 0)
cout << T.arr[v].data;
else
cout << ',' << T.arr[v].data;
visit[v] = 1;
if (T.arr[v].firstarc == NULL)
return;
for (int w = T.arr[v].firstarc->adj; w >= 0; w = find_num(T, v, w))
{
if (!visit[w])
preDFS(T, w);
}
}
int visited[100] = {0};
void postDFS(struct Node T, int v)
{
visit[v] = 1;
if (T.arr[v].firstarc == NULL)
return;
for (int w = T.arr[v].firstarc->adj; w >= 0; w = find_num(T, v, w))
{
if (!visited[w])
postDFS(T, w);
cout << T.arr[w].data << ',';
}
}
int leaf(struct Node T)
{
int sum = 0;
for (int i = 0; i < T.length; i++)
{
if (T.arr[i].firstarc == NULL)
sum++;
}
return sum;
}
int main()
{
vector<node> v;
struct node t;
char ch;
string s;
int len = 0;
while (cin >> t.data)
{
cin.get(ch);
t.parent = 0;
len++;
v.push_back(t);
if (ch == '\n')
break;
}
for (int i = 0; i < len; i++)
{
int num;
cin >> num;
v[i].parent = num;
}
struct Node T;
create(T, v, len);
preDFS(T, 0);
cout << endl;
postDFS(T, 0);
cout << T.arr[0].data << endl;
int sum;
sum = leaf(T);
cout << sum << endl;
return 0;
}