#include<iostream>
#include<vector>
using namespace std;
void Pref(vector <int> &P, vector <int> &S){
unsigned int t=0, n=S.size();
P.resize(n+1, 0);
for(unsigned int i=2; i<n; ++i){
while(t>0 && S[t+1]!=S[i])
t=P[t];
if(S[t+1]==S[i])
++t;
P[i]=t;
}
}
bool KMP(vector <int> &T, vector <int> &W){
//string S="#"+W+"#"+T;
vector <int> S;
S.push_back(-1);
for(int i=0; i<W.size(); ++i)S.push_back(W[i]);
S.push_back(-1);
for(int i=0; i<T.size(); ++i)S.push_back(T[i]);
vector <int> P;
Pref(P, S);
unsigned int ws=W.size();
for(unsigned int i=ws+2; i<S.size(); ++i){
if(P[i]==ws)
return true;
}
return false;
}
vector <int> tekst;
vector <int> tekst_c;
vector <int> wzor;
vector <int> t[512];
int n,m,a,x;
int main(){
ios_base::sync_with_stdio(0);
tekst.push_back(1);
cin>>n>>m;
for(int i=1; i<=n; ++i){
cin>>a;
for(int j=0; j<a; ++j){
cin>>x;
t[i].push_back(x);
}
}
for(int i=0; i<m; ++i){
cin>>x;
wzor.push_back(x);
}
int licznik=1;
while(tekst.size()<10000000){
++licznik;
tekst_c=tekst;
tekst.clear();
for(int i=0; i<tekst_c.size(); ++i){
for(int j=0; j<t[tekst_c[i]].size(); ++j){
tekst.push_back(t[tekst_c[i]][j]);
}
}
if(KMP(tekst,wzor)){
cout<<licznik<<endl;
return 0;
}
}
cout<<-1<<endl;
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 | #include<iostream> #include<vector> using namespace std; void Pref(vector <int> &P, vector <int> &S){ unsigned int t=0, n=S.size(); P.resize(n+1, 0); for(unsigned int i=2; i<n; ++i){ while(t>0 && S[t+1]!=S[i]) t=P[t]; if(S[t+1]==S[i]) ++t; P[i]=t; } } bool KMP(vector <int> &T, vector <int> &W){ //string S="#"+W+"#"+T; vector <int> S; S.push_back(-1); for(int i=0; i<W.size(); ++i)S.push_back(W[i]); S.push_back(-1); for(int i=0; i<T.size(); ++i)S.push_back(T[i]); vector <int> P; Pref(P, S); unsigned int ws=W.size(); for(unsigned int i=ws+2; i<S.size(); ++i){ if(P[i]==ws) return true; } return false; } vector <int> tekst; vector <int> tekst_c; vector <int> wzor; vector <int> t[512]; int n,m,a,x; int main(){ ios_base::sync_with_stdio(0); tekst.push_back(1); cin>>n>>m; for(int i=1; i<=n; ++i){ cin>>a; for(int j=0; j<a; ++j){ cin>>x; t[i].push_back(x); } } for(int i=0; i<m; ++i){ cin>>x; wzor.push_back(x); } int licznik=1; while(tekst.size()<10000000){ ++licznik; tekst_c=tekst; tekst.clear(); for(int i=0; i<tekst_c.size(); ++i){ for(int j=0; j<t[tekst_c[i]].size(); ++j){ tekst.push_back(t[tekst_c[i]][j]); } } if(KMP(tekst,wzor)){ cout<<licznik<<endl; return 0; } } cout<<-1<<endl; return 0; } |
English