input(没有多组输入):
5
11010
7
1110010
4
0000
output:
11111
1111110
0
题意:
给一个长度为 n 的01串 s ,要求从其中取出任意两个子串,将该两个子串按位或,能得到最大的值是多少,输出这个最大的01串(去除前导0).
思路:
首先,我们需要去除该串的前导0,因为这一段一定无法变成 1 ,对求解起不到任何左右。
其次,我们应该想到,其中一个子串一定是该串本身,这样最优。
最后就是如何最大化按位或收益。贪心地想,我们将一个高位的0变为1,收益要比将所有比它低位上的0变为1收益都大,所以,我们一定要尽可能地将最高位0变为1。
这是问题求解就显而易见了:设最高位0的位为 pos0 ,那么能影响该位的子串,其首部一定小于 pos0,所以我们只需要遍历所有开头小于pos0,长度刚好覆盖 pos0 ~ n - 1 的子串,逐个比较得出答案即可。
这道题比较坑的点在于,题目规则里解释了所有的01串 s 是随机生成的,也就是说任意一位为0或为1的概率均为 1 / 2 ,如果不是随机生成的话,该算法复杂度为 n ^ 2,显然超时 ,但现在我们的算法复杂度为 n log n 级别,于是可以轻松通过。
Code
#pragma GCC optimize(3)
#include<bits/stdc++.h>
#define endl "\n"
#define pb push_back
using namespace std;
typedef long long ll;
typedef pair<int,int> PII;
const int mod=1e9+7;
const int N=2e5+10;
const int inf=0x3f3f3f3f;
const ll INF=0x3f3f3f3f3f3f3f3f;
int t,n;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>n;
string s;
cin>>s;
int k=0;
int num=0;
while(s[k]=='0'&&num<=n)
{
++num;
++k;
}
s.erase(s.begin(),s.begin()+num);
n-=num;
int pos0=-1;
for(int i=0;i<n;i++)
{
if(s[i]=='0')
{
pos0=i;
break;
}
}
if(s.empty())
{
cout<<0<<endl;
return 0;
}
if(pos0==-1)
{
cout<<s<<endl;
return 0;
}
int v=n-pos0;
string ans=s;
for(int i=0;i<pos0;i++)
{
string temp=s;
for(int j=0;j<v;j++)
{
if(s[i+j]=='1')
{
temp[pos0+j]='1';
}
}
if(temp>ans)
ans=temp;
}
cout<<ans<<endl;
return 0;
}