80分求助
查看原帖
80分求助
682379
JiHuan楼主2024/3/24 22:54

WA #4,#6,用的是manacher+hash

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int N = 1e6 + 5;
const int mod = 1e9 + 7;

ull h[N], P[N];  //使用ull自然溢出
ll  Base = 13331;
void Hash(string s)
{
    int n=s.size();
    string t="#"+s;
    P[0]=1;
    for(int i=1;i<=n;i++)
    {
       P[i]=P[i-1]*Base;
    }
    h[0]=0;
    for(int i=1;i<=n;i++)
    { 
       h[i]=(h[i-1]*Base+(t[i]-'a'+1));
    }
}
ull query(int l,int r)
{
    return h[r]-h[l-1]*P[r-l+1];
}

int p[2*N];  //N需要不小于2*n+3;
//p[i]表示以i为中心的整个回文串长度(不算#),0表示长度为1。
//或者,算#时,代表回文半径,不包含中心。
auto manacher(string s)
{
	string t = "@#";
	for (auto& c : s)
	{
		t += c;
		t += '#';
	}
	t += '?';
	int n = t.size();
	int id = 0;   
	int mx = 0;
	int num = 0;  //num表示最长回文串长度,特点,全部初始化为0
	
for (int i = 1; i < n - 1; i++)  //起始字符和结束字符不需要计算
	{
		if (i < mx) p[i] = min(mx - i, p[2 * id - i]);
		while (t[i - p[i] - 1] == t[i + p[i] + 1]) p[i] += 1;
		if (i + p[i] > mx) id = i, mx = i + p[i];
		num = max(num, p[i]);
	}
	
	return num + (num == 0);
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0); 
    int n;
    cin>>n;
    string s;
    cin>>s;
    manacher(s);
    Hash(s);
    vector<pair<int,ull>> a;
    for(int i=2;i<=2*n;i+=2)
    {
        ull t=query(i/2-p[i]/2,i/2+p[i]/2);
        a.push_back(make_pair(p[i],t));
    }
    sort(a.begin(),a.end());
    for(int i=a.size()-1;i>=1;i--)
    {
        if(a[i].first==a[i-1].first&&a[i].second==a[i-1].second)
        {
            cout<<a[i].first/2+1;
            return 0;
        }
    }  
    cout<<0;
    return 0;
}
2024/3/24 22:54
加载中...