// Input n period, n ordinals, then candidate keys (all rotations). Output every feasible gap per key.
#include <iostream>
#include <vector>
using namespace std;
int main(){int n,p;cin>>n>>p;vector<int>x(n),k(p),pre(n+1);for(int &i:x)cin>>i;int all=(1<<p)-1;
 while(cin>>k[0]){for(int j=1;j<p;j++)cin>>k[j];int forbid[29]={};bool nz=false;
 for(int j=0;j<p;j++){forbid[k[j]]|=1<<j;nz|=k[j]!=0;}if(!nz)continue;
 int h=1;pre[0]=h;
 for(int i=0;i<n;i++){int a=h&~forbid[x[i]];h=(((a<<1)&all)|(a>>(p-1)))|(x[i]==0?h:0);pre[i+1]=h;}
 h=all;vector<int>gaps;
 for(int j=n-1;j>=1;j--){int a=(h>>1)|((h&1)<<(p-1));h=(a&~forbid[x[j]])|(x[j]==0?h:0);if(pre[j]&&(h&1))gaps.push_back(j);}
 if(!gaps.empty()){for(int i:k)cout<<i<<' ';cout<<gaps.size();for(auto j=gaps.rbegin();j!=gaps.rend();j++)cout<<' '<<*j;cout<<'\n';}
 }}
