54 lines
1.2 KiB
Python
54 lines
1.2 KiB
Python
|
from functools import cache
|
||
|
import bisect
|
||
|
import sys
|
||
|
|
||
|
base_limit = sys.getrecursionlimit()
|
||
|
|
||
|
def sc(cons):
|
||
|
return (cons*(cons+1))/2
|
||
|
|
||
|
def brutetop(a, b, k):
|
||
|
first = {}
|
||
|
for i in range(len(a)):
|
||
|
if a[i] not in first and a[i] != b[i]:
|
||
|
first[a[i]] = i
|
||
|
@cache
|
||
|
def brute(Q, i, cons):
|
||
|
if i == len(a):
|
||
|
return sc(cons)
|
||
|
|
||
|
if a[i] == b[i] or a[i] in Q:
|
||
|
return brute(Q, i+1, cons+1)
|
||
|
|
||
|
if len(Q) < k and (a[i] in first and i == first[a[i]]):
|
||
|
Qcop = list(Q)
|
||
|
bisect.insort(Qcop, a[i])
|
||
|
|
||
|
res1 = brute(Q, i+1, 0) + sc(cons)
|
||
|
res2 = brute(tuple(Qcop), i+1, cons+1)
|
||
|
|
||
|
return max(res1, res2)
|
||
|
|
||
|
return brute(Q, i+1, 0) + sc(cons)
|
||
|
|
||
|
return brute((), 0, 0)
|
||
|
|
||
|
def main():
|
||
|
ct = int(input())
|
||
|
ress = []
|
||
|
|
||
|
for _ in range(ct):
|
||
|
# len(a, b), char lim
|
||
|
n, k = [int(i) for i in input().split()]
|
||
|
a = input() # a = base string
|
||
|
b = input() # b = objective
|
||
|
|
||
|
sys.setrecursionlimit(max(len(a), base_limit))
|
||
|
print(int(brutetop(a, b, k)))
|
||
|
#ress.append(str(int(brutetop(a, b, k))))
|
||
|
#print("\n".join(ress))
|
||
|
|
||
|
|
||
|
|
||
|
main()
|