D.Say No to Palindromes(前缀和优化查询

D. Say No to Palindromes
题意:
定义一个字符串是好串,当且仅当 s s s 不包含任何长度大于等于 2 2 2 的回文子串。
给定一个长度为 n n n 的字符串(仅包含 a , b , c a,b,c a,b,c 三种字符)和 m m m 个询问,每次询问查询一个区间 [ l , r ] [l,r] [l,r],求将字符串 S l . . . r S_{l...r} Sl...r 变成好串至少需要修改多少字符。
思路:
因为字符串的组成仅有 3 3 3 种字符
模拟一下好串的特征,初始为 a a a,添加一个 b b b,下一个只能添加 c c c,否则 a b a aba aba 或者 a b b abb abb 都不是好串,再往后加只能加 a a a,就进入循环了,也就是好串仅有 a b c abc abc 这样的子串循环构成, a b c a b c a abcabca abcabca
a b c abc abc 这样的子串有 A 3 3 A_3^3 A33
维护一个由第 j j j 种子串构成字符串时,需要修改的字符个数的前缀和
code:

#include<bits/stdc++.h>
#define endl '\n'
#define ll long long
#define ull unsigned long long
#define ld long double
#define all(x) x.begin(), x.end()
#define mem(x, d) memset(x, d, sizeof(x))
#define eps 1e-6
using namespace std;
const int maxn = 2e5 + 9;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
ll n, m;
string s;
char t[6][5] = {"abc", "acb", "bac", "bca", "cab", "cba"};
int f[maxn][6];

void work()
{
	cin >> n >> m;
	cin >> s; s = "@" + s;
	for(int i = 1; i <= n; ++i){
		int k = (i - 1) % 3;
		for(int j = 0; j < 6; ++j)
			f[i][j] = f[i-1][j] + (s[i] != t[j][k]);
	}
	while(m--){
		int l, r;cin >> l >> r;
		int ans = inf;
		for(int i = 0; i < 6; ++i) ans = min(ans, f[r][i] - f[l-1][i]);
		cout << ans << endl;
	}	
}

int main()
{
	ios::sync_with_stdio(0);
//	int TT;cin>>TT;while(TT--)
	work();
	return 0;
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值