1. 程式人生 > 實用技巧 >Good Bye 2020 C

Good Bye 2020 C

Good Bye 2020 C

大意

給你一個僅由小寫字母組成的串,你可以將任意位置換成任意小寫字母。

問,你最少可以通過換幾個字母使得串中沒有長度大於一的迴文串。

思路

首先,一個長度較大的迴文串一定至少有一個長度較小的迴文串在其中心。

對於奇數長度,這個較小的串長度為 \(3\) ,對於偶數長度,為 \(2\)

如果我們將這個較小的迴文串破壞,顯然以此為中心的更大的迴文串(如果有)也會被破壞

因為小寫字母有 \(26\) 個,而較小長度的迴文串長度不超過 \(3\) ,所以,我們一定有一種替換方法,使得對於已經修改過的地方,不會生成新的迴文串,對於現有的迴文串,又能夠破壞掉它。

然後貪心的將每個迴文串的結束處的字母替換。

程式碼

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
using namespace std;

#define ll long long
#define ull unsigned long long
#define cint const int&
#define Pi acos(-1)

const int mod = 998244353;
const int inf_int = 0x7fffffff;
const ll inf_ll = 0x7fffffffffffffff;
const double ept = 1e-9;

int t, n;
int a[100100];

int main() {
    ios::sync_with_stdio(false);
    cin >> t;
    while(t--) {
        int ans=0;
        cin >> n;
        for(int i=1; i<=n; i++) cin >> a[i];
        a[n+1] = 0;
        sort(a+1, a+1+n);
        for(int i=n; i; i--) if(a[i+1] != a[i]){
            if(a[i+1] != a[i]+1) ++a[i];
            ++ans;
        }
        cout << ans << endl;
    }
    return 0;
}
/*
2
7
1 2 3 4 5 5 5
7
1 2 3 4 5 5 5
*/