#include "cstdio"
#include "vector"
using namespace std;
int n,m,x,xx,k,v,q,wynik=1,comp,t[2][10000005],w[1005],p[10000005];
vector <int> pom[505];
void pref()
{
p[0]=-1;
p[1]=k=0;
for (int i=2; i<=m; i++)
{
while (k>-1 && w[i]!=w[k+1]) k=p[k];
p[i]=++k;
}
}
bool kmp()
{
pref();
k=0;
for(int i=1; i<=q; i++)
{
while (k>-1 && t[x][i]!=w[k+1]) k=p[k];
if (++k==m) return true;
}
return false;
}
int main()
{
scanf ("%d%d", &n, &m);
for (int i=0; i<n; i++)
{
scanf ("%d", &x);
while (x--)
{
scanf ("%d", &v);
pom[i+1].push_back(v);
}
}
for (int i=1; i<=m; i++) scanf ("%d", &w[i]);
q=1;
x=0;
t[x][1]=1;
while (1)
{
if (kmp())
{
printf ("%d\n", wynik);
return 0;
}
if (comp>1e7+3)
{
printf ("-1\n");
return 0;
}
xx=(x+1)%2;
v=0;
for (int i=1; i<=q; i++)
{
for (int j=0; j<pom[t[x][i]].size(); j++)
{
v++;
t[xx][v]=pom[t[x][i]][j];
}
}
comp+=v;
q=v;
wynik++;
x++;
x%=2;
}
return 0;
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | #include "cstdio" #include "vector" using namespace std; int n,m,x,xx,k,v,q,wynik=1,comp,t[2][10000005],w[1005],p[10000005]; vector <int> pom[505]; void pref() { p[0]=-1; p[1]=k=0; for (int i=2; i<=m; i++) { while (k>-1 && w[i]!=w[k+1]) k=p[k]; p[i]=++k; } } bool kmp() { pref(); k=0; for(int i=1; i<=q; i++) { while (k>-1 && t[x][i]!=w[k+1]) k=p[k]; if (++k==m) return true; } return false; } int main() { scanf ("%d%d", &n, &m); for (int i=0; i<n; i++) { scanf ("%d", &x); while (x--) { scanf ("%d", &v); pom[i+1].push_back(v); } } for (int i=1; i<=m; i++) scanf ("%d", &w[i]); q=1; x=0; t[x][1]=1; while (1) { if (kmp()) { printf ("%d\n", wynik); return 0; } if (comp>1e7+3) { printf ("-1\n"); return 0; } xx=(x+1)%2; v=0; for (int i=1; i<=q; i++) { for (int j=0; j<pom[t[x][i]].size(); j++) { v++; t[xx][v]=pom[t[x][i]][j]; } } comp+=v; q=v; wynik++; x++; x%=2; } return 0; } |
English