Explanation
To solve this problem, we can use brute force and check every possible length of . Let and denote the number of zeros and ones in , respectively. The length of can be determined by . If this length is not an integer, then this is invalid and no further check is required for it.
For each possible length of , we want to check if the given pattern in matches the received signal . Let the hash of be . By pre-calculating the prefix sums of the hashes for , we can iterate through and check for each character in if the hash of its corresponding part in equals . This corresponding part in can be located if we use a pointer and increase it by every time we checked a character from . At the end, if all hashes match, then we have found a possible . Otherwise, if there is a mismatch at any point, we can terminate and go for the next possible length of .
Time Complexity
We first note that checking for a possible can be done in since for each character in , we can get the hash of its corresponding substring in in , given pre-processing to calculate the prefix sums of the hashes.
Then, let's determine that number of possible lengths of . Without loss of generality, suppose . As and are strict positive, must be less or equal to .
Therefore, the overall time complexity is .
Implementation
C++
#include <bits/stdc++.h>using namespace std;using ull = unsigned long long int;ull m = 1e9 + 9;ull base = 9973;// Hashes and powers start with 1vector<ull> rolling_hash;vector<ull> powers;
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!