-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSWESolver.py
More file actions
215 lines (202 loc) · 5.9 KB
/
SWESolver.py
File metadata and controls
215 lines (202 loc) · 5.9 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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import re, os, sys
from collections import deque
from functools import lru_cache
def parse_string(s_in):
raw = s_in.splitlines()
lines = [ln.strip() for ln in raw if ln.strip() != ""]
if not lines:
return None, "empty"
if not re.fullmatch(r"\d+", lines[0]):
return None, "bad k"
k = int(lines[0])
if len(lines) < 2 + k:
return None, "too short"
s = lines[1]
if not re.fullmatch(r"[a-z]*", s):
return None, "bad s"
ts = []
for i in range(2, 2 + k):
ti = lines[i]
if not re.fullmatch(r"[a-zA-Z]*", ti):
return None, "bad t"
ts.append(ti)
R = {}
for ln in lines[2 + k:]:
if ":" not in ln:
return None, "bad rule"
L, rhs = ln.split(":", 1)
L = L.strip()
rhs = rhs.strip()
if not re.fullmatch(r"[A-Z]", L):
return None, "bad Γ"
if L in R:
return None, "dup Γ"
if rhs == "":
return None, "empty domain"
parts = [p.strip() for p in rhs.split(",")]
if any(not re.fullmatch(r"[a-z]+", p) for p in parts):
return None, "bad domain word"
R[L] = parts
Gam_used = set("".join(re.findall(r"[A-Z]", "".join(ts))))
if not Gam_used.issubset(R.keys()):
return {"k": k, "s": s, "ts": ts, "R": {}}, None
return {"k": k, "s": s, "ts": ts, "R": R}, None
def all_substring_lengths(s):
n = len(s)
Ls = set()
for i in range(n):
for j in range(i + 1, n + 1):
Ls.add(j - i)
return Ls
def t_length_range(t, R):
mn = mx = 0
for ch in t:
if ch.islower():
mn += 1; mx += 1
else:
lens = [len(w) for w in R[ch]]
mn += min(lens); mx += max(lens)
return mn, mx
def expand(t, assign):
out = []
for ch in t:
if ch.islower():
out.append(ch)
else:
if ch not in assign:
return None
out.append(assign[ch])
return "".join(out)
def prune_domains_by_presence(R, s):
R2 = {}
for g, dom in R.items():
keep = [w for w in dom if w in s]
if not keep:
return None
keep.sort(key=len)
R2[g] = keep
return R2
@lru_cache(maxsize=100_000)
def build_regex_cached(t, assign_items, dom_key_tuple):
assign = dict(assign_items)
dom_map = dict(dom_key_tuple)
parts = []
for ch in t:
if ch.islower():
parts.append(ch)
else:
if ch in assign:
parts.append(re.escape(assign[ch]))
else:
dom = dom_map.get(ch, ())
if not dom:
return None
alts = "|".join(re.escape(w) for w in dom)
parts.append(f"(?:{alts})")
try:
return re.compile("".join(parts))
except re.error:
return None
def regex_feasible(s, t, assign, R):
if all(c.islower() or (c in assign) for c in t):
w = expand(t, assign)
return (w is not None) and (w in s)
used = sorted({c for c in t if c.isupper()})
dom_key_tuple = tuple((g, tuple(R[g])) for g in used)
assign_items = tuple(sorted(assign.items()))
reg = build_regex_cached(t, assign_items, dom_key_tuple)
if reg is None:
return False
return reg.search(s) is not None
def neighbors_in_t(t):
return [c for c in t if c.isupper()]
def AC3_regex(s, ts, R):
scopes = []
for idx, t in enumerate(ts):
vs = neighbors_in_t(t)
if vs:
scopes.append((idx, t, tuple(sorted(set(vs)))))
from collections import deque
Q = deque()
for _, t, scope in scopes:
for g in scope:
Q.append((t, g))
while Q:
t, g = Q.popleft()
dom = R[g]
new_dom = []
for v in dom:
if regex_feasible(s, t, {g: v}, R):
new_dom.append(v)
if not new_dom:
return None
if len(new_dom) != len(dom):
R[g] = new_dom
for _, t2, scope2 in scopes:
if g in scope2:
for g2 in scope2:
if g2 != g:
Q.append((t2, g2))
return R
def solve(instance):
s, ts, R = instance["s"], instance["ts"], dict(instance["R"])
if not R:
return None
for t in ts:
if all(c.islower() for c in t) and (t not in s):
return None
R = prune_domains_by_presence(R, s)
if R is None:
return None
Ls = all_substring_lengths(s)
for t in ts:
mn, mx = t_length_range(t, R)
if not any(L in Ls for L in range(mn, mx + 1)):
return None
R = AC3_regex(s, ts, R)
if R is None:
return None
Gam = sorted(R.keys())
freq = {g: sum(g in t for t in ts) for g in Gam}
order = sorted(Gam, key=lambda g: (len(R[g]), -freq[g]))
@lru_cache(maxsize=200_000)
def dfs(idx, packed_assign):
assign = dict(packed_assign)
for t in ts:
if not regex_feasible(s, t, assign, R):
return False
if idx == len(order):
return True
g = order[idx]
for v in R[g]:
assign[g] = v
pa = tuple(sorted(assign.items()))
if dfs(idx + 1, pa):
return True
assign.pop(g, None)
return False
ok = dfs(0, tuple())
if not ok:
return None
assign = {}
for i, g in enumerate(order):
for v in R[g]:
assign[g] = v
pa = tuple(sorted(assign.items()))
if dfs(i + 1, pa):
break
else:
return None
return {g: assign[g] for g in sorted(assign)}
# Read file from standard input
data = sys.stdin.read()
inst, err = parse_string(data)
if err is not None:
print("NO")
else:
sol = solve(inst)
if sol is None:
print("NO")
else:
for g, w in sol.items():
print(f"{g}:{w}")