跳到正文

题解

题解:P16960 [SCCPC 2026] 那一天的回文字符串

原文
文章信息与版本

文章信息

收录
2026年6月24日
更新
2026年6月24日
篇幅
约 3 分钟
题目
P16960

版本

  1. v1当前

题目传送门

思路

我觉得这个思路挺巧妙的。

首先我们注意到偶数位与奇数位上的字母无法进行交换,我们不妨开两个桶:一个为奇数桶,一个为偶数桶,分别记录在奇数位和偶数位上不同字母出现的次数。

首先我们先来考虑字符串长度为偶数的情况:这时,每一个奇数位都必须有一个偶数位与其相对应,且字母相同,形式化的:奇数桶与偶数桶完全相同说明可以把字符串变成一个回文串,反之则不行。

我们再考虑字符串长度为奇数的情况:与字符串长度为偶数时条件唯一不同的是:在原条件的基础上,要求中间位所在的桶中恰好有一个字母出现奇数次(放在中间位),另一个桶中所有字母都出现偶数次(两两配对到对称位置)。满足则可以,反之则不行。

代码

C++
#include<iostream>
#include<cmath>
#include<algorithm>
#define int long long
#define is ios::sync_with_stdio(false);cin.tie(nullptr);

using namespace std;

int T;
string s;

signed main(void){
	is
    cin >> T;
    while(T --){
        string s;
        cin >> s;
        int len = s.size();
        int t[2][26] = {};
        for(int i = 0; i < len; i ++)t[i % 2][s[i] - 'a'] ++;
        bool flag = true;
        if(len % 2 == 0){
            for(int i = 0; i < 26; i ++)
                if(t[0][i] != t[1][i]){
                    flag = false;
                    break;
                }
        }
		else{
            int idx = len / 2;
            int c = idx % 2;
            int cnt[2] = {0};
            for(int i = 0; i < 2; i ++)
                for(int j = 0; j < 26; j ++)
                    if(t[i][j] % 2 == 1)
                        cnt[i] ++;
            if(!(cnt[c] == 1 && cnt[c ^ 1] == 0))
                flag = false;
        }
        cout << (flag ? "YES" : "NO") << "\n";
    }
	return 0;
}
原文