跳到正文

个人记录

8.27总结

_JX__约 6 分钟
原文
文章信息与版本

文章信息

发布
2026年8月27日
收录
2026年8月30日
更新
2026年11月3日
篇幅
约 6 分钟

版本

  1. v1当前

T1

用map统计哈希值出现的次数,答案是哈希值出现的最多次数。

但是需要用unordered_map,不然我会TLE

C++
#include<bits/stdc++.h>
using namespace std;
const unsigned long long p=13331,N=5e6+5;
unsigned long long hs[N],pw[N];
unordered_map<unsigned long long,int> mp;
unsigned long long get_hs(int l,int r)
{
	return hs[r]-hs[l-1]*pw[r-l+1];
}
signed main()
{
	string s;
	cin>>s;
	s='#'+s;
	pw[0]=1;
	int n=s.size();
	for(int i=1;i<=n;i++)
	{
		pw[i]=pw[i-1]*p;
		hs[i]=hs[i-1]*p+s[i];
	}
	int k;
	cin>>k;
	int Max=0;
	for(int i=1;i+k-1<=n;i++)
	{
		unsigned long long x=get_hs(i,k+i-1);
		mp[x]++;
		Max=max(Max,mp[x]);
	}
	cout<<Max;
	return 0;
}

T2

通过预处理每个字符串的前缀哈希和后缀哈希,枚举每一个可能被删除的位置,将去掉该位置后的前后两段哈希值组合成特征值,再对所有字符串的特征值进行排序并统计相同特征值的数量,从而高效计算出恰好只有一位不同的字符串对数。

pre[i][j]:存储第 i 个字符串从第 1 位到第 j 位的哈希值。

suf[i][j]:存储第 i 个字符串从第 j 位到最后一位的哈希值

C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int p=131,N=3e5+5;
int n,l,f[205],pre[N][205],suf[N][205];
string s;
pair<int,int> op[N];
signed main()
{
	cin>>n>>l>>s;
	for(int i=1;i<=n;i++)
	{
		cin>>s;
		s="#"+s;
		for(int j=1;j<=l;j++)
			pre[i][j]=pre[i][j-1]*p+s[j];
		for(int j=l;j>=1;j--)
			suf[i][j]=suf[i][j+1]*p+s[j];
	}
	int ans=0;
	for(int i=1;i<=l;i++)
	{
		for(int j=1;j<=n;j++)
		{
			op[j].first=pre[j][i-1];
			op[j].second=suf[j][i+1];
		}
		sort(op+1,op+n+1);
		int L=1,r=1;
		while(r<=n)
		{
			while(op[L]==op[r]&&r<=n)
				r++;
			r--;
			ans+=(r-L+1)*(r-L)/2;
			L=r+1;
			r++;
		}
	}
	cout<<ans;
	return 0;
}

T3

用了双指针结合字符串哈希与二分查找的贪心策略;在归并两个数组时,若当前指针指向的元素不同则直接取较小者;若元素相同,则通过二分查找配合预处理的前缀哈希,快速定位两个数组从当前位置开始的最长公共前缀,随后比较公共前缀之后的下一个元素大小,优先选择后续字典序更小的那个数组的元素,从而保证最终归并出的序列字典序最小。

C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N=4e5+5,p=131;
int n,m;
int hsa[N],hsb[N],ans[N],pw[N],a[N],b[N];
void pre()
{
	pw[0]=1;
	for(int i=1;i<=N;i++)
		pw[i]=pw[i-1]*p;
	for(int i=1;i<=n;i++)
		hsa[i]=hsa[i-1]*p+a[i];
	for(int i=1;i<=m;i++)
		hsb[i]=hsb[i-1]*p+b[i];
}
int get_hsa(int l,int r)
{
	return hsa[r]-hsa[l-1]*pw[r-l+1];
}
int get_hsb(int l,int r)
{
	return hsb[r]-hsb[l-1]*pw[r-l+1];
}
signed main()
{
	cin>>n;
	for(int i=1;i<=n;i++)
		cin>>a[i];
	cin>>m;
	for(int i=1;i<=m;i++)
		cin>>b[i];
	pre();
	int x=1,y=1;
	while(x<=n&&y<=m)
	{
		if(a[x]!=b[y])
		{
			if(a[x]<b[y])
			{
				cout<<a[x];
				x++;
			}
			else
			{
				cout<<b[y];
				y++;
			}
		}
		else
		{
			int l=0,r=min(n-x+1,m-y+1)+1;
			while(l+1<r)
			{
				int mid=(l+r)/2;
				if(get_hsa(x,x+mid-1)==get_hsb(y,y+mid-1))
					l=mid;
				else
					r=mid;
			}
			int res=l;
			if(x+res-1==n)
				cout<<b[y++];
			else if(y+res-1==m)
				cout<<a[x++];
			else
			{
				if(a[x+res]<b[y+res])
					cout<<a[x++];
				else
					cout<<b[y++];
			}
		}
		cout<<" ";
	}
	while(x<=n)
		cout<<a[x++]<<" ";
	while(y<=m)
		cout<<b[y++]<<" ";
	return 0;
}
原文