Pretty Good Proportion (Large)

Time limit5sMemory limit512 MB

Summary
Given a binary string and a target fraction F, find the smallest starting position among substrings whose proportion of 1s is closest to F.
Level

Medium7 of 10

Topics
Prefix sum, Sorting
Solved
No attempts yet

Problem

You have a string of NN binary digits. You want a substring whose proportion of 1s is exactly some target value, but such a substring may not exist, so a close one will do.

Given a decimal fraction FF, find a substring whose proportion of 1s is as close to FF as possible. The proportion of 1s of a substring is the number of 1s in it divided by its length. A substring is a run of consecutive characters and its length is at least 1. Report the smallest starting position among the substrings that come closest.

Input

The first line contains the number of test cases TT. TT test cases follow.

Each test case begins with a line containing NN and FF, separated by one space. FF is a decimal fraction between 0 and 1 inclusive, written with exactly 6 digits after the decimal point. The next line contains NN digits, each 0 or 1, with no spaces.

Limits

  • 1≤T≤1001 \le T \le 100
  • 0≤F≤10 \le F \le 1
  • FF has exactly 6 digits after the decimal point
  • 1≤N≤5000001 \le N \le 500000

Output

For each test case, print one line of the form Case #x: y. Here xx is the test case number starting from 1, and yy is the starting position of a substring whose proportion of 1s is as close to FF as possible. Positions are counted from 0. When several starting positions are possible, print the smallest one.

Explanation

Take F=0.666667F = 0.666667 and the string 001001010111. No substring has a proportion of 1s equal to 666667/1000000666667/1000000, and the closest reachable value is 2/32/3. Five substrings reach it: 101, 101, 011 of length 3 starting at positions 5, 7, 8, and 101011, 010111 of length 6 starting at positions 5 and 6. The smallest of those starting positions is 5.

Examples2

  1. Example 1

    Input
    5
    12 0.666667
    001001010111
    11 0.400000
    10000100011
    9 0.000000
    111110111
    5 1.000000
    00000
    15 0.333333
    000000000011000
    
    Expected output
    Case #1: 5
    Case #2: 5
    Case #3: 5
    Case #4: 0
    Case #5: 6
    
  2. Example 2

    Input
    3
    2 0.500000
    01
    2 0.500000
    10
    3 0.500000
    110
    
    Expected output
    Case #1: 0
    Case #2: 0
    Case #3: 1