#include<iostream> #include<vector> #define MAX 20001111 using namespace std; vector<int>tab[600]; vector<int>chwil; vector<int>chwil1; int txt[MAX]; int ile[MAX]; void kmp(int d){ int t=0; for(int i=2;i<=d;i++) { while((t>0) && (txt[t] != txt[i-1])) t = ile[t]; if(txt[t] == txt[i-1]) t++; ile[i] = t; } } int main(){ int n,m; cin >> n >> m; int a,b; for(int i=1;i<=n;i++){ cin >> a; for(int j=0;j<a;j++){ cin >> b; tab[i].push_back(b); } } bool spr1=false; for(int i=0;i<m;i++) cin >> txt[i]; if(m==1 && txt[0] == 1){ cout << "1"; spr1=true; } else{ txt[m] = 2000; txt[m+1] = 1; int d=m+1; int x=m; bool spr = false; int wyn=1; while(1){ if(wyn > 7000) break; wyn++; for(int i=m+1;i<=d;i++) chwil.push_back(txt[i]); if(chwil.size() * 6 < MAX){ for(int i=0;i<chwil.size();i++){ for(int j=0;j<tab[chwil[i]].size();j++){ x++; txt[x] = tab[chwil[i]][j]; } } d=x; x=m; kmp(d); for(int i=m+1;i<=d;i++) if(ile[i] >= m){ spr = true; break; } if(spr) break; for(int i=0;i<=d;i++) ile[i] = 0; chwil = chwil1; } else break; } if(spr) cout << wyn; if(!spr && !spr1) cout << "-1"; } 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 79 80 81 82 83 84 85 86 | #include<iostream> #include<vector> #define MAX 20001111 using namespace std; vector<int>tab[600]; vector<int>chwil; vector<int>chwil1; int txt[MAX]; int ile[MAX]; void kmp(int d){ int t=0; for(int i=2;i<=d;i++) { while((t>0) && (txt[t] != txt[i-1])) t = ile[t]; if(txt[t] == txt[i-1]) t++; ile[i] = t; } } int main(){ int n,m; cin >> n >> m; int a,b; for(int i=1;i<=n;i++){ cin >> a; for(int j=0;j<a;j++){ cin >> b; tab[i].push_back(b); } } bool spr1=false; for(int i=0;i<m;i++) cin >> txt[i]; if(m==1 && txt[0] == 1){ cout << "1"; spr1=true; } else{ txt[m] = 2000; txt[m+1] = 1; int d=m+1; int x=m; bool spr = false; int wyn=1; while(1){ if(wyn > 7000) break; wyn++; for(int i=m+1;i<=d;i++) chwil.push_back(txt[i]); if(chwil.size() * 6 < MAX){ for(int i=0;i<chwil.size();i++){ for(int j=0;j<tab[chwil[i]].size();j++){ x++; txt[x] = tab[chwil[i]][j]; } } d=x; x=m; kmp(d); for(int i=m+1;i<=d;i++) if(ile[i] >= m){ spr = true; break; } if(spr) break; for(int i=0;i<=d;i++) ile[i] = 0; chwil = chwil1; } else break; } if(spr) cout << wyn; if(!spr && !spr1) cout << "-1"; } return 0; } |