kipsora
2021-12-10 00:32:42 +08:00
可能说得不是很清楚,花了点时间写了个法 2 的代码:
```python3
P = 177
MOD = 192073433
def main():
strings = input().split(",")
string_hashes = []
max_string_length = 0
for string in strings:
hashes = [0]
for i in range(len(string)):
hashes.append((hashes[-1] * P + ord(string[i])) % MOD)
string_hashes.append(hashes)
max_string_length = max(max_string_length, len(string))
pows = [1] # P ** i
for i in range(max_string_length + 1):
pows.append(pows[-1] * P % MOD)
sorted_indices = list(range(len(strings)))
sorted_indices = sorted(sorted_indices, key=lambda i: len(strings[i]))
disabled_hashes = set()
answers = [None for _ in strings]
for i in sorted_indices:
string = strings[i]
hashes = string_hashes[i]
hash_to_be_disabled = []
min_length = len(string) + 1
for x in range(len(string)):
for y in range(x, len(string)):
substr_hash = (hashes[y + 1] - hashes[x] * pows[y + 1 - x]) % MOD
substr_hash = (substr_hash + MOD) % MOD
hash_to_be_disabled.append(substr_hash)
if substr_hash not in disabled_hashes and min_length > (y - x + 1):
min_length = y - x + 1
answers[i] = (x, y)
disabled_hashes.update(hash_to_be_disabled)
print(",".join([strings[i][x: y + 1] for i, (x, y) in enumerate(answers)]))
if __name__ == "__main__":
main()
```
输入:dev1,dev2,dev3,v3a,abc,bc
输出:d,2,ev3,v,ab,b
输入:abcabc,a,ab,abc,abca,abcab
输出:cabc,a,b,c,ca,cab
输入:a,aa,aaa,aaaa,aaaaa,aaaaaa
输出:a,aa,aaa,aaaa,aaaaa,aaaaaa
输入:ab,cd,abc,cde,abcd,cdab,cdabb,cac,cab,cacd
输出:a,c,bc,e,bcd,da,bb,ca,cab,acd
题主你给的这个例子似乎也有些问题,v3 应该能同时表示 dev3 和 v3a ,而 v3a 更小,所以其实 dev3 的特征串只能是 ev3 而不能是 v3