#include <iostream>
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn = 105;
queue<char> v[maxn]; ///存储每个轨道上的物品
stack<char> s; ///筐
queue<char> q; ///结果输出
int main()
{
int N,M,S;
int a[1005];
char ch;
cin>>N>>M>>S;
getchar();
for(int i=1;i<=N;i++){
for(int j=0;j<M;j++){
cin>>ch;
v[i].push(ch);
a[i]++;
}
getchar();
}
int x;
while(true){
cin>>x;
if(x==-1)break;
if(x==0){
if(s.size()==0)continue; //如果筐里面的为空就不做任何处理,跳过
else{
q.push(s.top()); //否则,弹出栈顶元素,放入流水线上
s.pop();
}
}
if(x>=1 && x<=N){
if(v[x].size()==0)continue; //如果对应轨道上没有物品了不做任何处理,跳过
else{
if(s.size()==S){ //如果筐已经满了,就弹出筐顶物品到流水线上,再将物品放入框中
q.push(s.top());
s.pop();
}
s.push(v[x].front());
v[x].pop();
}
}
}
/*
for(int i=0;i<N;i++){
for(int j=0;j<M;j++){
cout<<v[i][j];
}
}
*/
while(!q.empty()){
cout<<q.front();
q.pop();
}
return 0;
}
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1e4 + 10,M=1000010;
int h[N],e[M],ne[M],idx;
int n;
int cnt;
bool vis[N];
vector<int> temp,ans;
void add(int a,int b){
e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
void dfs(int u,int sum){
if(sum>cnt){
cnt=sum;
ans=temp;
}
else if(sum==cnt&&temp<ans){
ans=temp;
}
for(int i=h[u];~i;i=ne[i]){
int j=e[i];
temp.push_back(j);
dfs(j,sum+1);
temp.pop_back();
}
}
int main()
{
memset(h,-1,sizeof h);
cin>>n;
for(int i=0;i<n;i++){
int k;
cin>>k;
while(k--){
int a;
cin>>a;
add(i,a);
vis[a]=true;
}
}
int root=0;
while(vis[root])root++;
dfs(root,1);
cout<<cnt<<endl;
cout<<root;
for(int i=0;i<ans.size();i++){
cout<<' '<<ans[i];
}
return 0;
}