[NOIP2024] 编辑字符串 解题报告
题目大意
将一个字符串中可以交换位置的字符相邻地交换若干次,最大化
题目分析
先考虑弱化的问题怎么做:
除了被固定的字符,其余字符可任意交换(不必相邻)。
这个问题是好做的,找到可用
这个问题虽然弱化了,但能带来一些启发:
-
- 不能交换的数字将可以交换的数字隔开了,如果解除固定,那解法就和弱化问题一样了(甚至更弱)。
回到原问题,考虑样例。
将可以自由交换的字符打包分割成一个块。
这样每个块内的元素可以互相交换,再由对弱化问题的观察,可以有一个类似的贪心做法。
先将原字符串分块,统计处块内可用的
对于求解,贪心地匹配。假设当前在
写代码其实是简单的,分块注意点细节就行。
赛时代码:
#include <bits/stdc++.h>
using namespace std;
inline int read()
{
int w=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9')
{
if(ch=='-') f=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9')
{
w=(w<<1)+(w<<3)+(ch^48);
ch=getchar();
}
return w*f;
}
inline void write(int x)
{
if(x<0)
{
putchar('-');
x=-x;
}
if(x>9) write(x/10);
putchar(x%10+'0');
}
const int maxn=1e5+10;
int T,n;
string s1,s2,t1,t2;
int cnt1=0,cnt2=0;
int num1[3][maxn],num0[3][maxn];
int st1[maxn],ed1[maxn],st2[maxn],ed2[maxn];
int main()
{
// freopen("edit.in","r",stdin);
// freopen("edit.out","w",stdout);
T=read();
while(T--)
{
n=read();
cin>>s1>>s2>>t1>>t2;
s1=" "+s1,s2=" "+s2,t1=" "+t1,t2=" "+t2;
int ans=0;
cnt1=cnt2=0;
memset(num1,0,sizeof num1);
memset(num0,0,sizeof num0);
memset(st1,0,sizeof st1);
memset(st2,0,sizeof st2);
memset(ed1,0,sizeof ed1);
memset(ed2,0,sizeof ed2);
for(int i=1;i<=n;)
{
if(t1[i]=='0')
{
++cnt1;
if(s1[i]=='0') num0[1][cnt1]++;
else num1[1][cnt1]++;
st1[cnt1]=ed1[cnt1]=i;
++i;
continue;
}
++cnt1;
st1[cnt1]=i;
while(t1[i]!='0'&&i<=n)
{
if(s1[i]=='1') num1[1][cnt1]++;
else num0[1][cnt1]++;
++i;
}
ed1[cnt1]=i-1;
}
for(int i=1;i<=n;)
{
if(t2[i]=='0')
{
++cnt2;
if(s2[i]=='0') num0[2][cnt2]++;
else num1[2][cnt2]++;
st2[cnt2]=ed2[cnt2]=i;
++i;
continue;
}
++cnt2;
st2[cnt2]=i;
while(t2[i]!='0'&&i<=n)
{
if(s2[i]=='1') num1[2][cnt2]++;
else num0[2][cnt2]++;
++i;
}
ed2[cnt2]=i-1;
}
int i=1,j=1;
for(int p=1;p<=n;++p)
{
if(num0[1][i]>0&&num0[2][j]>0)
{
num0[1][i]--,num0[2][j]--;
++ans;
}
else if(num1[1][i]>0&&num1[2][j]>0)
{
num1[1][i]--,num1[2][j]--;
++ans;
}
if(p+1>ed1[i]) ++i;
if(p+1>ed2[j]) ++j;
}
cout<<ans<<endl;
}
return 0;
}
后话
- 考场看错题了,看成问题弱化版,浪费 30min。
- T1 总共用时 1h30min ,赢!
- NOIp rp++