题解:P6312 [PA2018] Palindrom

P6312 题解

题面

原题传送门

题意

题目的意思非常简单,就是给定一个字符串 \(s\),问 \(s\) 是否为回文串。

前置知识

  1. 哈希

(没了,真的很简单)

思路(解法)

首先,哈希都会吧?不会的先看

其实判断回文最简单的就是分别求从头开始和从尾开始的哈希值,比较即可。

那么哈希值又是怎么求的呢?

先设 \(a,b\) 分别为从头开始和从尾开始的哈希值。

求哈希值得:

\(\begin{aligned} a=\sum_{i=1}^nbase^i\times s[i]\pmod m,b=\sum_{i=1}^nbase^{n-i+1}\times s[i]\pmod m\end{aligned}\)

于是,我们就得到到了以下代码。

代码(\(10\) 分)

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
const int base=157;
const int mod=123456791;
const int MN=20000005;
int n,num[MN],a,b;
char s[MN];
bool flag;
void init(){
	num[1]=1;
	for(int i=2; i<=n; i++) num[i]=(num[i-1]*base)%mod; 
}
int main(){
	scanf("%d",&n);
	cin>>s+1;
	n=strlen(s+1);
	init();//预处理 
	for(int i=1; i<=n; i++){
		a=(a+s[i]*num[i])%mod;
		b=(b+s[i]*num[n-i+1])%mod;//哈希求值 
	}
	if(a==b) printf("TAK");
	else printf("NIE");
	return 0;
}

可以发现,这段代码成功的 MLE 了,所以我们就不能设数组,要将 \(base\) 进行动态处理,且字符串也要拆成字符输入,于是就有。

AC 代码(一点点小改动)

首先既然要拆成字符输入,不妨设 \(hash1,hash2\) 分别为从头开始和从尾开始的哈希值。

于是易知:

\(hash1_i=(hash1_{i-1}+base^i\times ch)\)

接下来考虑反过来的,其哈希值就等于每次在最后面补一位。

\(hash2_i=(hash2_{i-1}\times base+ch)\)

于是代码就出来了:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
const int base=157;
const int mod=123456791;
const int MN=20000005;
long long n,a,b,num=1;
char ch;
bool flag;
int main(){
	scanf("%lld",&n);
	while(1){
	    ch=getchar();
	    if(ch<'a'||ch>'z') break;
		a=(a*base+ch)%mod;
		b=(b+num*ch)%mod;
		num=num*base%mod;
	}
	if(a==b) printf("TAK");
	else printf("NIE");
	return 0;
}
posted @ 2025-01-29 15:49  naroto2022  阅读(16)  评论(0)    收藏  举报