跳到正文

题解

[NOIP2024] 编辑字符串 解题报告

vanueber约 5 分钟
原文
文章信息与版本

文章信息

发布
2024年12月11日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 5 分钟
题目
P11361

版本

  1. v1当前

题目大意

将一个字符串中可以交换位置的字符相邻地交换若干次,最大化 ∑i=1n[ai=bi]\sum_{i=1}^{n}[a_i=b_i]。

题目分析

先考虑弱化的问题怎么做:

除了被固定的字符,其余字符可任意交换(不必相邻)。

这个问题是好做的,找到可用 00 和可用 11,贪心地扫一遍即可。

这个问题虽然弱化了,但能带来一些启发:

  1. 00 和 11 的优先级是相同的,一个匹配的位置要为 0,10,1 均可,那么填 00 和 填 11 最终答案不会变。
  2. 不能交换的数字将可以交换的数字隔开了,如果解除固定,那解法就和弱化问题一样了(甚至更弱)。

回到原问题,考虑样例。

将可以自由交换的字符打包分割成一个块。

[011][1][0][1][1][1][10][1][0][011][1][0][1] \\ [1][1][10][1][0]

这样每个块内的元素可以互相交换,再由对弱化问题的观察,可以有一个类似的贪心做法。

先将原字符串分块,统计处块内可用的 0,10,1 数量。

对于求解,贪心地匹配。假设当前在 aa 的第 ii 个块,bb 的第 jj 个块,如果可以用 00 占位,将 ai,0,bj,0a_{i,0},b_{j,0} 减一,如果是 11 同理。

写代码其实是简单的,分块注意点细节就行。

赛时代码:

C++
#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;
}

后话

  1. 考场看错题了,看成问题弱化版,浪费 30min。
  2. T1 总共用时 1h30min ,赢!
  3. NOIp rp++
原文