Educational Codeforces Round 92 (Rated for Div. 2) C. Good String

本文探讨了Codeforces竞赛中的一道题——构造良好字符串。通过分析字符串的左右循环移位,阐述了如何找到最小删除字符数使字符串满足特定条件。文章提供了详细的解题思路与AC代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Educational Codeforces Round 92 (Rated for Div. 2) C. Good String

题目链接

Let’s call left cyclic shift of some string t1t2t3…tn−1tn as string t2t3…tn−1tnt1.

Analogically, let’s call right cyclic shift of string t as string tnt1t2t3…tn−1.

Let’s say string t is good if its left cyclic shift is equal to its right cyclic shift.

You are given string s which consists of digits 0–9.

What is the minimum number of characters you need to erase from s to make it good?

Input

The first line contains single integer t (1≤t≤1000) — the number of test cases.

Next t lines contains test cases — one per line. The first and only line of each test case contains string s (2≤|s|≤2⋅105). Each character si is digit 0–9.

It’s guaranteed that the total length of strings doesn’t exceed 2e5.

Output

For each test case, print the minimum number of characters you need to erase from s to make it good.

Example

input

3
95831
100120013
252525252525

output

3
5
0

思维题~
我们只需要观察变化的字符串即可,有两种情况:

  1. 字符串首尾不同,例如 a x x x x b axxxxb axxxxb
    变化后得到: x x x x b a xxxxba xxxxba b a x x x x baxxxx baxxxx,如果两个相等就发现字符串就是 a b a b ⋯ abab\cdots abab 这样循环

  2. 字符串首尾相同,很容易发现就是一个字母全部相同的字符串才符合条件

那么对第一种情况就可以暴力所有 a b ab ab 的组合,对第二种情况统计每一个数字的数量即可,AC代码如下:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
string s;
int solve(){
    int len=s.size(),ans=len;
    for(int i=0;i<10;i++){
        ans=min(ans,len-count(s.begin(),s.end(),char('0'+i)));
        for(int j=0;j<10;j++){
            if(i==j)continue;
            int flag=0,sum=0;
            for(int k=0;k<len;k++){
                if(flag%2==0&&s[k]-'0'==i) flag++;
                else if(flag%2&&s[k]-'0'==j) flag++,sum++;
            }
            ans=min(ans,len-sum*2);
        }
    }
    return ans;
}
int main(){
    int t;
    cin>>t;
    while(t--){
        cin>>s;
        cout<<solve()<<endl;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

旺 崽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值