Educational Codeforces Round 53 (Rated for Div. 2)

A. Diverse Substring(前缀和)

题意:给一个字符串,找出一个子串满足该子串中每个字母出现的次数不超过子串的长度/2,字符串的长度n<1000.

题解:n方枚举子串的起点和终点,对于每个字母建一个前缀和就能知道在任意一个字串中每个字母出现的个数了。

代码:

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

char s[1010];
int n;
int num[30][1010];

int main(){
    scanf("%d", &n);
    scanf("%s", s+1);
    for(int i = 1; i<=n; i++){
        for(int k = 0; k<27; k++){
            num[k][i] = num[k][i-1];
        }
        num[s[i]-'a'][i] = num[s[i]-'a'][i-1]+1;
    }
    int l = -1, r = -1;
    for(int i = 1; i<=n; i++){
        for(int j = 1; j<=i; j++){
            bool flag = true;
            for(int k = 0; k<28; k++){
                if(num[k][i]-num[k][j-1]>(i-j+1)/2){
                    flag = false;
                    break;
                }
            }
            if(flag == true){
                l = j; r = i;
            }
        }
    }
    if(l!=-1 && r!=-1){
        cout<<"YES"<<endl;
        for(int i = l; i<=r; i++){
            cout<<s[i];
        }
        cout<<endl;
    }
    else{
        cout<<"NO"<<endl;
    }

    return 0;
}

猜你喜欢

转载自www.cnblogs.com/grimcake/p/9859052.html