power oj 2610 hash——強大而又溫柔的暴力

判斷迴文串

Time Limit: 2000 MS Memory Limit: 4096 KB
Total Submit: 298 Accepted: 50 Page View: 525
Submit Status Discuss

某天吃飯的時候,FM有了一個帥氣idea,其實是個傻逼題?題意很簡單,給一個字符串判斷是否是迴文串?
PS:如果一個字符串正着讀和反着讀都一樣,那麼這個字符串爲迴文串,比如aba,cc,cddc爲迴文串,而ac,acda,adA則不是迴文串。

多組輸入,第一行爲nn,代表字符串的長度。
第二行爲這個字符串,該串僅包含大小寫字母。
是迴文串輸出"YES", 不是迴文串輸出 "NO"。
8
aaaaaaaa
7
tangcan
3
lyl
YES
NO
YES
迴文串長度 1len1071≤len≤107,請注意內存限制。

題意:中文題目不解釋
思路:1e7的長度,4M的內存限制,別幻想開數組暴力了,正解爲hash,先hash前面一半的再hash後面的那一半然後判斷前後hash值是否相等,據說洋哥卡掉了單hash,要用雙hash,不過我比較頭鐵單雙hash都嘗試了,居然都過了,可能是我用的mod很少見,沒有被卡掉,所以在學習hash的時候要用別人很少用的mod和base值,這樣出題人就很難卡你了。hash很強大,可以深入學習哈

代碼:

#include<stdio.h>
#include<string.h>
#include<cmath>
#include<stdlib.h>
#include<time.h>
#include<algorithm>
#include<iostream>
#include<vector>
#include<queue>
#define ll long long
#define ull unsigned long long
#define qq printf("QAQ\n");
using namespace std;
const int maxn=1e5+5;
const int inf=0x3f3f3f3f;
const ll mod=1e9+7;
const ull hmod1=1e9+97;
const ull hmod2=1e9+93;
const ull base1=133;
const ull base2=131;
const double e=exp(1.0);
const double pi=acos(-1);
int main()
{
	int n;
	ll a,b,c,d,b1,b2;
	while(scanf("%d",&n)!=EOF)
	{
		char cc;
		a=0,b=0;
		getchar();
		for(int i=1;i<=n/2;i++)
		{
			cc=getchar();
			a=(a*base1+(ull)cc)%hmod1;
			b=(b*base2+(ull)cc)%hmod2;
		}
		
		if(n&1)getchar();
		b1=1,b2=1,c=0,d=0;
		for(int i=1;i<=n/2;i++)
		{
			cc=getchar();
			c=(c+(ull)cc*b1)%hmod1;
			d=(d+(ull)cc*b2)%hmod2;
			
			b1=(b1*base1)%hmod1;
			b2=(b2*base2)%hmod2;
		}
		//if(a==c)printf("YES\n");
		if(a==c&&b==d)printf("YES\n");
		else printf("NO\n");
	}
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章