-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathuva843.py
55 lines (45 loc) · 1.26 KB
/
uva843.py
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
import sys
n = int(input())
all_words = []
for i in range(n):
all_words.append(input())
def match(idx):
if idx == len(words):
return True
word = words[idx] # encrypted word
for w in all_words:
if len(word) != len(w):
continue
success = True
added = set()
for i, c in enumerate(word):
if (c in mapping and mapping[c] != w[i]) or (c not in mapping and w[i] in mapped):
for c in added:
mapped.remove(mapping[c])
del mapping[c]
success = False
break
if c not in mapping:
mapping[c] = w[i]
mapped.add(w[i])
added.add(c)
if not success:
continue
if match(idx+1):
return True
else:
for c in added:
mapped.remove(mapping[c])
del mapping[c]
return False
for line in sys.stdin:
words = line.split()
mapping = {}
mapped = set()
found_match = match(0)
for i, word in enumerate(words):
for c in word:
print(mapping[c] if found_match else '*', end='')
if i != len(words)-1:
print(' ', end='')
print('')