About ABC468D

· · 题解

lg传送门

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

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

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

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

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

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

AC Code:

#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。