Educational Codeforces Round 137 (Rated for Div. 2) D. Problem with Random Tests
The first observation we need is that we can choose two prefixes of s s s as the substrings used in forming the results. This can be proved easily: suppose we chose a substring which does not contain the leftmost character of s s s; if we expand it to the left, the answer won’t become worse. So, it is optimal to choose two prefixes of s s s as the substrings.
Furthermore, one of these prefixes must be s s s itself: if the leftmost index of 1 is i i i, the length of the answer won’t exceed n − i + 1 n−i+1 n−i+1, but the only way to have a 1 in the (n−i+1)-th bit of the answer is to choose a prefix of s s s where the ( n − i + 1 ) (n−i+1) (n−i+1)-th character (from the right) is 1; and there is only one such prefix of s s s, which is s s s itself.
So, now we can solve the problem in O ( n 2 ) O(n^2) O(n2) — try to combine all prefixes of s s s with s s s itself, and choose the one that yields the best answer. To speed this up, we need to somehow cut down on the number of prefixes of s s s we check.
Let’s look at the first block of 1’s in s s s. The next character after this block is 0; since we take s s s as one of the substring, in order to get 1 instead of 0 in the corresponding position of the answer, we need to choose a prefix which has 1 in that position. This 1 represents one of the 1’s from the first block of 1’s, since only one of them can shift to that position. So, we need to check only the prefixes such that, by using them, we shift some character 1 from the first block to the position of the first 0 after this block. Since the tests are random, the expected length of the first block of 1’s is O ( 1 ) O(1) O(1) (furthermore, even the probabiliy that its length is 20 or bigger is about 1 0 − 6 10^{−6} 10−6), so the expected number of prefixes we need to check is also O ( 1 ) O(1) O(1). Thus, the expected runtime of our solution is O ( n ) O(n) O(n).
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;cin>>n;
string s;cin>>s;
if(string(n,'0')==s)
{
cout<<"0"<<endl;
return 0;
}
int poss=0;
while(s[poss]=='0') poss++;
int pos=n;
for(int i=poss;i<n;i++)
if(s[i]=='0')
{
pos=i;
break;
}
string mx=s;
int len=n-pos;
vector<string> b;
for(int i=poss;i<n-len;i++)
if(s[i]=='1')
b.push_back(s.substr(i,len));
for(auto ss:b)
{
string t=s;
for(int i=pos,j=0;i<n;i++,j++)
t[i]=(t[i]|ss[j]);
mx=max(mx,t);
}
cout<<mx.substr(poss)<<endl;
return 0;
}