read_line.to_i.times do puts solve() end def solve n, m = read_line.split.map(&.to_i) s = read_line.chars r = manacher(s) max = 0 (n * 2).times do |i| if i % 2 == 1 len = (r[i] + 1) // 2 max = {max, len * 2 - 1}.max else len = r[i] // 2 max = {max, len * 2}.max end end return 1 if m <= max r = manacher(s + s) max = 0 rep = false (n * 4).times do |i| next if !(i - r[i] <= 2 * n && 2 * n <= i + r[i]) if i % 2 == 1 len = (r[i] + 1) // 2 if len * 2 - 1 > max max = len * 2 - 1 rem = s[..(i // 2 - len)] if rem == rem.reverse rep = true end end else len = r[i] // 2 if len * 2 > max max = len * 2 rem = s[..(i // 2 - 1 - len)] if rem == rem.reverse rep = true end end end end # puts [r, max, rep] return 2 if m <= max if rep (m - max + n - 1) // n + 2 else -1 end end def manacher(s) str = ['$'] s.each do |c| str << c << '$' end i = 0 j = 0 rad = Array.new(str.size, 0) while i < str.size while i - j >= 0 && i + j < str.size && str[i - j] == str[i + j] j += 1 end rad[i] = j k = 1 while k <= i && k + rad[i - k] < j rad[i + k] = rad[i - k] k += 1 end i += k j -= k end rad # pos = 1.step(to: str.size - 1, by: 2).max_by { |i| rad[i] } # len = (rad[pos] + 1) // 2 # odd_max = {(pos - rad[pos] + 1) // 2, len * 2 - 1} # pos = 0.step(to: str.size - 1, by: 2).max_by { |i| rad[i] } # len = rad[pos] // 2 # even_max = {(pos - rad[pos] + 1) // 2, len * 2} end