跳到正文

个人记录

About ABC468D

Mengchen_Yxf2013_qwq约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年7月26日
收录
2026年7月26日
更新
2026年11月15日
篇幅
约 4 分钟

版本

  1. v1当前

lg传送门

此题解中,设字符串长度为 nn,下标从 11 到 nn。

首先分析如何判断一个字符串是不是好字符串。 对字符串 TT,使用双指针分别指向串首尾,指针相向遍历,并统计对称位置字符不匹配的组数(即遍历时两个指针指向的字符不同的情况有几个)。若不匹配组数不超过 1,则 TT 是好字符串。

注意到对于 N=104N=10^4,可以通过时间复杂度为 O(N2)O(N^2) 的方案。对于现有的判断好字符串的方案,主要是由首尾向中心,则枚举首尾就需要 O(N2)O(N^2) 的时间复杂度,不可行。不妨考虑枚举中心,让双指针从中心开始向两边扩展,并用相同的方法判断,枚举部分优化到了 O(N)O(N)。

分别考虑长度为奇数和偶数的字符串:

  • 对于长度为奇数的字符串,中心就是最中间的字符。如字符串 yandw,它的中心为 n。
  • 对于长度为偶数的字符串,中心取前一半的最后一个字符。如字符串 ylovew,它的中心为 o。

此时考虑对于一个中心,如何扩展。分别枚举长度为奇数的字符串的中心和长度为偶数的字符串的中心。设双指针为 ll、rr,不难得出:

  • 对于长度为奇数的字符串的中心,ll、rr 均初始化为该中心。此时中心可为 11 到 nn。
  • 对于长度为偶数的字符串的中心,ll 初始化为该中心,rr 初始化为该中心的下一个。由于 rr 的初始化,此时中心可为 11 到 n−1n-1。

此时,考虑扩展什么时候结束。如上述方案,记录在扩展时两指针对应的字符不同的次数,记为dd。每次扩展判断一次,若 d>1d > 1,则已经超出了好字符串的限制,就算继续扩展也不可能会再是好字符串了(dd 只会增加,不会减少)。此时即可停止此次扩展。若 d≤1d \le 1,则答案加一,并继续扩展。

AC Code:

C++
#include <bits/stdc++.h>
#define el "\n"
#define sp " "
#define fi first
#define se second
#define inf 1e18
#define r0 return 0
#define int long long
#define F(i, a, b, c) for (int i = a; i <= b; i += c)
#define debug printf ("bug is in here\n")
#define TheEnd continue
#define base(s) s = sp + s
#define lcm(a, b) a / __gcd(a, b) * b
#define setp(x) fixed << setprecision(x)
#define getmid(l, r) l + (r - l) / 2

using namespace std;

typedef long long ll;
typedef string str;
using ull = unsigned long long;

str s;
int n;
//o&e mid
signed main(void) {
	std::ios::sync_with_stdio(false);
	std::cin.tie(0);
	std::cout.tie(0);
	cin >> s;
	n = s.size();
	base(s);
	int ans = 0;
	F(i, 1, n, 1) {//odd
		int l = i, r = i;
		int d = 0;
		while (l > 0 && r <= n && l <= r) {
			if (s[l] != s[r]) {
				d++;
			}
			if (d > 1) {
				break;
			}
			ans++;
			l--, r++;
		}
	}
	F(i, 1, n, 1) {//even
		int l = i, r = i + 1;
		int d = 0;
		while (l > 0 && r <= n && l <= r) {
			if (s[l] != s[r]) {
				d++;
			}
			if (d > 1) {
				break;
			}
			ans++;
			l--, r++;
		}
	}
	cout << ans << el;
	r0;
}
//Yuexingfei_qwq is a flying-wind

赛时AC记录

求过,thk。

原文