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

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
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;
    }
}

你可能感兴趣的:(思维,暴力,Codeforces)