#ifndef LOCAL
#pragma GCC Optimize("O3,Ofast,unroll-loops")
#pragma GCC Target("bmi,bmi2,avx,avx2")
#endif
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
#define int ll
#define f first
#define s second
#define mp make_pair
#define pb push_back
#define pii pair<int, int>
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin() (x).rend()
#ifndef LOCAL
#define endl "\n"
#endif
mt19937 rnd(11);
void solve() {
int n, m;
cin >> n >> m;
vector<vector<int>> graph(n);
for (int i = 0; i < m; ++i) {
int a, b;
cin >> a >> b;
--a; --b;
graph[a].pb(b);
graph[b].pb(a);
}
int k;
cin >> k;
vector<pii> bad(n, mp(0, 0));
map<pii, pii> badE;
for (int i = 0; i < k; ++i) {
int sz;
cin >> sz;
vector<int> v(sz);
for (auto &x : v) {
cin >> x;
--x;
}
for (int j = 0; j < sz; ++j) {
bad[v[j]] = mp(sz, j);
badE[mp(v[j], v[(j + 1) % v.size()])] = mp(sz, j);
badE[mp(v[(j + 1) % v.size()], v[j])] = mp(sz, j);
}
}
int T = n * 4;
vector<int> d(n, 1e9);
d[0] = 0;
priority_queue<pii> q;
q.push(mp(0, 0));
vector<int> marked(n, false);
auto ok = [&](int v, int t) {
return (bad[v].f == 0 || (t % bad[v].f != bad[v].s));
};
while (!q.empty()) {
int i = q.top().s;
q.pop();
if (marked[i]) {
continue;
}
int t = d[i];
marked[i] = true;
for (auto &u : graph[i]) {
if (ok(u, t + 1) && (badE[mp(i, u)].f == 0 || (t % badE[mp(i, u)].f != badE[mp(i, u)].s))) {
if (d[u] > t + 1) {
d[u] = t + 1;
q.push(mp(-d[u], u));
}
}
}
t = d[i] + 1;
if (ok(i, t)) {
for (auto &u : graph[i]) {
if (ok(u, t + 1) && (badE[mp(i, u)].f == 0 || (t % badE[mp(i, u)].f != badE[mp(i, u)].s))) {
if (d[u] > t + 1) {
d[u] = t + 1;
q.push(mp(-d[u], u));
}
}
}
}
}
if (d[n - 1] == 1e9) {
cout << "impossible" << endl;
} else {
cout << d[n - 1] << endl;
}
}
signed main() {
#ifdef LOCAL
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#else
ios::sync_with_stdio(false);
cin.tie(0);
#endif
int t = 1;
// cin >> t;
while (t--) {
solve();
}
}
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |