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 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| #include <bits/stdc++.h> #define pii pair<int, int>
using namespace std; const int N = 110, P = 1 << 12; vector<int> G[N], E[N]; int d[N][P]; int g[11][11]; int key[N]; int n, m, p, k, s; bool vis[N][P]; set<pii> edge;
inline int read() { int x = 0, y = 1; char c = getchar(); while (c < '0' || c > '9') {if (c == '-') y = -1; c = getchar();} while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar(); return x * y; }
inline void add(int a, int b, int c) { G[a].push_back(b); E[a].push_back(c); }
inline void build() { int dx[4] = {1, -1, 0, 0}, dy[4] = {0, 0, 1, -1}; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) for (int k = 0; k < 4; k++) { int u = i + dx[k], v = j + dy[k]; if (!u || u > n || !v || v > m) continue; if (!edge.count({g[i][j], g[u][v]})) add(g[i][j], g[u][v], 0), add(g[u][v], g[i][j], 0); } }
inline int bfs() { memset(d, 0x3f, sizeof d); d[1][0] = 0; deque<pii> q; q.push_front({1, 0}); while (q.size()) { pii t = q.front(); q.pop_front(); int u = t.first, st = t.second; if (u == n * m) return d[u][st]; if (vis[u][st]) continue; vis[u][st] = 1; if (key[u]) { int state = st | key[u]; if (d[u][state] > d[u][st]) { d[u][state] = d[u][st]; q.push_front({u, state}); } } for (int i = 0; i < G[u].size(); i++) { int v = G[u][i], w = E[u][i]; if (w && !(st >> w & 1)) continue; if (d[v][st] > d[u][st] + 1) { d[v][st] = d[u][st] + 1; q.push_back({v, st}); } } } return -1; }
int main() { n = read(), m = read(), p = read(), k = read(); for (int i = 1, idx = 0; i <= n; i++) for (int j = 1; j <= m; j++) g[i][j] = ++idx;
while (k--) { int x1 = read(), y1 = read(), x2 = read(), y2 = read(), c = read(); edge.insert({g[x1][y1], g[x2][y2]}), edge.insert({g[x2][y2], g[x1][y1]}); if (c) add(g[x1][y1], g[x2][y2], c), add(g[x2][y2], g[x1][y1], c); } build(); s = read(); while (s--) { int x = read(), y = read(), q = read(); key[g[x][y]] |= 1 << q; } printf("%d\n", bfs()); return 0; }
|