-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0156.cpp
More file actions
131 lines (101 loc) · 2.54 KB
/
0156.cpp
File metadata and controls
131 lines (101 loc) · 2.54 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
// https://coderun.yandex.ru/problem/typos
// string rewriting + shortest path (BFS) + meet-in-the-middle (depth 2+2) + hashing
#include <bits/stdc++.h>
using namespace std;
typedef string str;
typedef unordered_map<str,int> umsi;
typedef queue<str> qs;
#define sz(x) (int)(x).size()
#define rep(i,a,b) for (int i = (a); i <= (b); ++i)
#define pb push_back
#define fi first
#define se second
#define rsr(v,n) (v).reserve(n)
struct rule { str a, b; };
typedef vector<rule> vr;
static umsi reach(const str& start, const vr& rules, int maxd)
{
umsi dist;
rsr(dist, 4096);
qs q;
dist[start] = 0;
q.push(start);
while (!q.empty())
{
str cur = q.front();
q.pop();
int d = dist[cur];
if (d == maxd) continue;
for (auto &r : rules)
{
const str &from = r.a;
const str &to = r.b;
size_t pos = 0;
while (true)
{
pos = cur.find(from, pos);
if (pos == str::npos) break;
str nxt;
rsr(nxt, sz(cur) - sz(from) + sz(to));
nxt.append(cur, 0, pos);
nxt += to;
nxt.append(cur, pos + sz(from), str::npos);
if (nxt != cur)
{
auto it = dist.find(nxt);
if (it == dist.end() || it->se > d + 1)
{ dist[nxt] = d + 1; q.push(nxt); }
}
pos = pos + 1;
}
}
}
return dist;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
str s, t;
if (!(cin >> s)) return 0;
cin >> t;
int n;
cin >> n;
vr fwd, bwd;
rsr(fwd, n);
rsr(bwd, n);
rep(i, 1, n)
{
str a, b;
cin >> a >> b;
fwd.pb({a, b});
bwd.pb({b, a});
}
if (s == t) { cout << 0 << '\n'; return 0; }
umsi d1 = reach(s, fwd, 2);
umsi d2 = reach(t, bwd, 2);
int ans = 1e9;
auto it1 = d1.find(t);
if (it1 != d1.end()) ans = min(ans, it1->se);
auto it2 = d2.find(s);
if (it2 != d2.end()) ans = min(ans, it2->se);
if (sz(d1) <= sz(d2))
{
for (auto &kv : d1)
{
auto it = d2.find(kv.fi);
if (it != d2.end()) ans = min(ans, kv.se + it->se);
}
}
else
{
for (auto &kv : d2)
{
auto it = d1.find(kv.fi);
if (it != d1.end()) ans = min(ans, kv.se + it->se);
}
}
if (ans > 4) ans = -1;
cout << ans << '\n';
return 0;
}