#include <stdint.h>
#include <vector>
#include <iostream>
#include <utility>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
unsigned int n, m;
cin >> n >> m;
vector< vector<int> > reps(n);
for(unsigned int i = 0; i < n; ++i) {
int l;
cin >> l;
reps[i].resize(l);
for(int j = 0; j < l; ++j) {
cin >> reps[i][j]; --reps[i][j];
}
}
vector<int> needle(m);
for(unsigned int i = 0; i < m; ++i) {
cin >> needle[i]; --needle[i];
}
vector<int> pmt(m + 1);
{
pmt[0] = -1;
pmt[1] = 0;
for(unsigned int i = 2, s = 0; i <= m; ++i) {
while(needle[i - 1] != needle[s] and s != 0) s = pmt[s];
s += (needle[i - 1] == needle[s]);
pmt[i] = s;
}
}
unsigned int const LIMIT = 50000000;
vector< pair<int16_t, int16_t> > hay;
hay.push_back(make_pair<int16_t, int16_t>(0, 1));
for(unsigned int i = 0, s = 0; i < LIMIT ; ++i) {
int v = hay[i].first;
int d = hay[i].second;
for(unsigned int k = 0; k < reps[v].size() and hay.size() <= LIMIT; ++k) hay.push_back(make_pair<int16_t, int16_t>(reps[v][k], d + 1));
if(i != 0 and d != hay[i - 1].second) s = 0;
while(v != needle[s] and s) s = pmt[s];
s += (v == needle[s]);
if(s == m) {
cout << d << '\n';
return 0;
}
}
cout << "-1\n";
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 | #include <stdint.h> #include <vector> #include <iostream> #include <utility> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); unsigned int n, m; cin >> n >> m; vector< vector<int> > reps(n); for(unsigned int i = 0; i < n; ++i) { int l; cin >> l; reps[i].resize(l); for(int j = 0; j < l; ++j) { cin >> reps[i][j]; --reps[i][j]; } } vector<int> needle(m); for(unsigned int i = 0; i < m; ++i) { cin >> needle[i]; --needle[i]; } vector<int> pmt(m + 1); { pmt[0] = -1; pmt[1] = 0; for(unsigned int i = 2, s = 0; i <= m; ++i) { while(needle[i - 1] != needle[s] and s != 0) s = pmt[s]; s += (needle[i - 1] == needle[s]); pmt[i] = s; } } unsigned int const LIMIT = 50000000; vector< pair<int16_t, int16_t> > hay; hay.push_back(make_pair<int16_t, int16_t>(0, 1)); for(unsigned int i = 0, s = 0; i < LIMIT ; ++i) { int v = hay[i].first; int d = hay[i].second; for(unsigned int k = 0; k < reps[v].size() and hay.size() <= LIMIT; ++k) hay.push_back(make_pair<int16_t, int16_t>(reps[v][k], d + 1)); if(i != 0 and d != hay[i - 1].second) s = 0; while(v != needle[s] and s) s = pmt[s]; s += (v == needle[s]); if(s == m) { cout << d << '\n'; return 0; } } cout << "-1\n"; return 0; } |
English