D. Say No to Palindromes (dp+思维)

D. Say No to Palindromes

题目链接

大致题意:

给出一个字符串以及字符串的长度n,有m次询问,每次询问给出l,r,求区间l,r不存在长度大于2的回文串最少需要进行几次修改(只包含abc三种字符,修改也只能包含abc三种字符)


解题思路:

对于只有abc三个字符构成的字符串,使得其不存在长度大于2的回文串,必然是存在循环节的,即abcabcabc这样

那么对于三种字符,循环节的种类有六种,我们需要处理出字符串对于每个循环节需要做出的修改次数

f[i][j]表示对于第i个循环节,到第j个字符时,需要修改的次数

对于区间查询,答案就是六种循环节中区间修改次数最少的那一种


AC代码:

#include <bits/stdc++.h>
#define rep(i, n) for (int i = 1; i <= (n); ++i)
#define debug(a) cout << #a << " = " << a << endl;
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const int N = 2e5 + 10;
int n, m;
string a[6] = { "abc","acb","bac","bca","cab","cba" };
int f[6][N];
int main(void)
{
	ios::sync_with_stdio(0); cin.tie(0);
	cin >> n >> m;
	string s; cin >> s;
	for (int i = 0; i < 6; ++i)
		for (int j = 1; j <= n; ++j)
			f[i][j] = f[i][j - 1] + (a[i][(j - 1) % 3] != s[j - 1]);
	while (m--) {
		int l, r; cin >> l >> r;
		int res = INF;
		for (int i = 0; i < 6; ++i)
			res = min(res, f[i][r] - f[i][l - 1]);
		cout << res << endl;
	}
	return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值