Barbecue
题目链接
题意 :
给出一个长度为 N 的序列 S ,随后给出 Q 次询问,每次询问都会给出 l,r ,代表取出 S 的子串 S′ 。对于这个子串 S′ 进行操作,规定如下:
每一回合,拿到子串的选手需要丢弃这个子串的第一个或者最后一个字母,随后将操作后的子串交给下一个选手;
当子串为回文时,拥有这个子串的选手输掉了比赛;
双方均采取最优策略,对于每一个询问,输出胜者。
思路 :
若初始串为回文串,则后手胜;否则每轮开始时玩家拿到的字符串都不是回文串.若此时玩家必败,即删除第一个或最后一个字符都会使得剩下的字符串是回文串,则此时的串只能形如a b , a b a b , a b a b a b , ⋯ ,⋯,这表明必败态的长度是偶数,故谁胜只与起始串长度的奇偶有关.
若每次询问都用Manacher算法判断回文串,时间复杂度O ( n q ),会TLE.考虑用字符串哈希O ( n ) 预处理,每次询问O ( 1 ) 查询,时间复杂度O ( n + q )
马拉车AC代码 :
#include <bits/stdc++.h>
using namespace std;
#define LL long long
const int N = 2e6 + 10;
char s[N << 1];
int p[N << 1];
int n, q; string ss;
void manacher(){
s[0] = '-', s[1] = '#';
for (int i = 0; i < n; i ++ ){
s[2 * i + 2] = ss[i];
s[2 * i + 3] = '#';
}
n = n * 2 + 1;
s[n + 1] = '+';
int mid = 0, r = 0;
for (int i = 1; i < n; i ++ ){
if (i < r) p[i] = min(p[(mid << 1) - i], r - i);
else p[i] = 1;
while(s[i - p[i]] == s[i + p[i]]) p[i]++;
if (i + p[i] > r){
r = i + p[i];
mid = i;
}
}
}
int main() {
ios::sync_with_stdio(false); cin.tie(0);
cin >> n >> q >> ss;
manacher();
for (int i = 1; i <= q; ++ i) {
int x, y;
cin >> x >> y;
int xx = x, yy = y;
x *= 2, y *= 2;
int mid = (x + y) / 2;
if ( 2 * p[mid] - 1 >= y - x + 1) cout << "Budada\n";
else {
if ((yy - xx + 1) % 2 == 0) cout << "Budada\n";
else cout << "Putata\n";
}
}
return 0;
}
字符串哈希AC代码 :
#include<iostream>
#include<string>
#include<cstring>
#include<map>
#include<set>
#include<cmath>
#include<sstream>
#include<cstdio>
#include<vector>
#include<stack>
#include<queue>
#include<algorithm>
#include<list>
#define IOS ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define PII pair<int,int>
#define inf 0x3f3f3f3f
#define endl "\n"
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
const double pi = acos(-1.0);
ll t,n,m,k;
const int maxn = 1e6+6;
const int M = 13331;
ull hash1[maxn],hash2[maxn],p[maxn];
void init()
{
p[0] = 1;
for(int i = 1 ; i < maxn ; i++) p[i] = p[i - 1] * M;
}
ull gethash1(int l,int r)
{
return hash1[r] - hash1[l - 1] * p[r - l + 1];
}
ull gethash2(int l,int r)
{
return hash2[l] - hash2[r + 1] * p[r - l + 1];
}
void solve()
{
cin >> n >> m;
init();
string s;
cin >> s;
s = " " + s;
int len = s.size() - 1;
hash1[0] = hash2[len + 1] = 0;
for(int i = 1 ; i < s.size() ; i++){
hash1[i] = hash1[i - 1] *M + s[i] - 'a';
hash2[len - i + 1] = hash2[len - i + 2] * M + s[len + 1 - i] - 'a';
}
while(m--){
int l,r;
cin >> l >> r;
if((r - l + 1) % 2 == 0) cout << "Budada" << endl;
else if(gethash1(l,r) == gethash2(l,r)) cout << "Budada" << endl;
else cout << "Putata" << endl;
}
}
int main() {
IOS;
solve();
// cin >> t;
// while(t--) solve();
return 0;
}