#include <bits/stdc++.h>
#define ll long long
#define pb push_back
#define maxn 100010
#define mmaxn 1000000000
#define pii pair<int,int>
#define pll pair<ll int,ll int>
#define pdd pair<double,double>
#define MOD 1000000007
#define f first
#define s second
using namespace std;
vector<int> nodes[maxn/5];
bool visit[maxn];
map <string,bool > inserted;
vector<string> t[maxn];
vector<pair<pii,int>> qu;
bool compare(const pair<pii,int> &i, const pair<pii,int> &j){
if(i.s!=j.s){
return i.f.s < j.f.s ;
}
else{
if(i.f.f != j.f.f) // level check
return i.f.f > j.f.f;
else
return i.f.s < j.f.s ;
}
}
void dfs(int x,int p,int cnt,int compo){
visit[x]=true;
qu.pb({{cnt,x},compo});
for(auto i:nodes[x]){
if(i!=p && !visit[i])
dfs(i,x,cnt+1,compo);
}
}
int main(){
int q,n,m,d,dt,kids;
cin>>q;
while(q--){
cin>>n>>m;
vector<int> base;
for(int i=1;i<=n;i++){
cin>>d;
while(d--){
cin>>dt;
nodes[i].pb(dt);
// nodes[i].pb(dt);
}
}
for(int i=0;i<m;i++){
cin>>dt;
base.pb(dt);
}
// cout<<"boop\n";
int cnt=0;
vector<string> k;
qu.clear();
for(auto i:base){
dfs(i,-1,0,cnt);
cnt++;
}
// sort(k.begin(), k.end());
sort(qu.begin(), qu.end(),compare);
cout<<qu.size()<<"\n";
// vector<string> g;
for(auto i:qu){
// g.insert(g.end(),i.begin(),i.end());
// cout<<i.f.f<<" "<<i.f.s<<" "<<i.s<<"\n";
cout<<i.f.s<<" ";
}
cout<<"\n";
}
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CiNkZWZpbmUgbGwgbG9uZyBsb25nCiNkZWZpbmUgcGIgcHVzaF9iYWNrCiNkZWZpbmUgbWF4biAxMDAwMTAKI2RlZmluZSBtbWF4biAxMDAwMDAwMDAwCiNkZWZpbmUgcGlpIHBhaXI8aW50LGludD4KI2RlZmluZSBwbGwgcGFpcjxsbCBpbnQsbGwgaW50PgojZGVmaW5lIHBkZCBwYWlyPGRvdWJs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