跳到正文

题解

题解:P15702 [2018 KAIST RUN Spring] Winter Olympic Games

lujiayi654321约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年7月6日
收录
2026年7月14日
更新
2026年11月10日
篇幅
约 4 分钟
获赞
1
题目
P15702

版本

  1. v1当前

Solution

记替换的区间为 [l,r][l,r]。

注意到左端点 ll 必然是第一个 0\mathtt{0} 所在的位置。
否则,如果在左边,我们会白白删去一些 1\mathtt{1},不优;如果在右边,我们在前面留下了一些 0\mathtt{0},更劣。得证。

中间的一段被替换成 1\mathtt{1} 之后,我们希望后面的部分字典序越大越好。于是找到 ll 之后,固定左端点,只需要 [r+1,n][r+1,n] 的字典序尽可能大即可。机房大佬 yy:“上后缀排序板子。”
然鹅,蒟蒻并不会后缀排序。

考虑怎么快速比较后缀串的大小,可以对后缀做字符串哈希,比较两个串时只需要对哈希值二分查找,找到第一处不一样的字符,然后比较这个字符的大小即可。

这就做完了?

万恶的数据卡掉了我的哈希,于是只能写双哈希。调不出来不嘻嘻。

对于字符串中没有 0\mathtt{0} 的情况需要特判,由于子段可以为空,直接随便插入一个 1\mathtt{1} 即可。

Code

时间复杂度 O(nlog⁡n)\mathcal{O}(n\log n)。

AC Code
C++
#include <iostream>
#define re register
const int N=1e6+6;
typedef unsigned long long ULL;
const ULL B1=13331;
typedef long long LL;
const LL B2=5233,Mod=1e9+7;
int n;
char s[N];
ULL hash1[N],base1[N];
LL hash2[N],base2[N];
inline void init(const int n) {
	base1[0]=B1,base2[0]=B2;
	for(re int i=1;i<=n;++i)
		base1[i]=base1[i-1]*B1,
		base2[i]=base2[i-1]*B2%Mod;
}
inline ULL get_hash1(int l,int r) {
	return hash1[r]-hash1[l-1]*base1[r-l];
}
inline LL get_hash2(int l,int r) {
	return ((hash2[r]-hash2[l-1]*base2[r-l])%Mod+Mod)%Mod;
}
inline bool cmp(int i,int j)
{
	if(s[i]>s[j]) return false;
	int l=j,r=n,ans=j-1;
	while(l<=r)
	{
		int mid=l+r>>1;
		if(get_hash1(j,mid)!=get_hash1(i,i+mid-j) || get_hash2(j,mid)!=get_hash2(i,i+mid-j))
			r=mid-1;
		else l=mid+1,ans=mid;
	}  // 二分查找第一个不同字符的位置
	if(ans==n || s[ans+1]<s[i+ans-j+1])
		return false;
	return true;
}
int main()
{
	std::ios::sync_with_stdio(false),
	std::cin.tie(0);
	std::cin>>n>>s+1;
	init(n);
	int L=0; while(s[++L]!='0' && L!=n);  // 找到第一个 0 的位置
	if(L==n && s[n]!='0')
	{
		std::cout<<"0 0";
		return 0;
	}  // 特判
	for(re int i=L;i<=n;++i)
		hash1[i]=hash1[i-1]*B1+s[i],
		hash2[i]=(hash2[i-1]*B2+s[i])%Mod;
	// 双哈希
	int ans=L;
	for(re int i=L+1;i<=n;++i)
		if(cmp(ans,i)) ans=i;
	std::cout<<L-1<<' '<<ans-L;
	return 0;
}
原文