cf round #849 D. Distinct Split

Let's denote the f(x)function for a string xas the number of distinct characters that the string contains. For example f(abc)=3, f(bbbbb)=1, and f(babacaba)=3.

Given a string s, split it into two non-empty strings aand bsuch that f(a)+f(b)is the maximum possible. In other words, find the maximum possible value of f(a)+f(b)
such that a+b=s(the concatenation of string aand string bis equal to string s).

Input
The input consists of multiple test cases. The first line contains an integer t(1≤t≤104) — the number of test cases. The description of the test cases follows.

The first line of each test case contains an integer n(2≤n≤2⋅105) — the length of the string s.

The second line contains the string s, consisting of lowercase English letters.

It is guaranteed that the sum of nover all test cases does not exceed 2⋅105.

Output

For each test case, output a single integer — the maximum possible value of f(a)+f(b)such that a+b=s.


这道题的大意就是把一个字符串截成两段,然后分别计算它们包含多少不重复字符。
一开始想的是暴力,虽然样例过了但是显然最终会爆内存。
然后开始观察题意:
由于截成两段,因此最大结果不会超过52(26*2)。
思路:
因为只有两段,因此可以设两个内存分别为26的数组来代表左右两部分。

然后开始遍历原字符串,首先从头的时候全部是属于right数组,因此可以提前计算整个数组的字母数量并存入right数组中,
然后在遍历的过程中right数组会不断减少,当减少为0的时候总和减一,同时left数组没有一位从0到1总和就加一,每循环
一次就取最大值,等于52或等于字符串最大值的时候可以停止遍历。

代码如下

#include<algorithm>
#include<iostream>
#include<cstring>
#include<map>
using namespace std;
int main()
{
    int n;
    cin>>n;
    while(n--) {
        int m,ans=0,sum=0;
        string s;
        cin>>m>>s;
        int te[26],l[26];
        memset(te,0,sizeof te);
        memset(l,0,sizeof l);
        for(int i=0;i<m;i++) te[s[i]-'a']++;
        for(int i=0;i<26;i++)
            if(te[i])
                sum++;
        //cout<<"x"<<sum<<endl;
        for(int i=0;i<m-1;i++) {
            int k = s[i]-'a';
            l[k]+=1;
            te[k]-=1;
            if(te[k]==0) sum--;
            if(l[k]==1) sum++;
            //cout<<"xxx:"<<l[k]<<" "<<te[k]<<endl;
            ans = max(ans,sum);
        }

        printf("%d\n",ans);
    }

    return 0;
}

posted on 2023-02-18 22:36  呆唯可可爱爱  阅读(37)  评论(0)    收藏  举报

导航