bzoj 2213: [Poi2011]Difference

Description

A word consisting of lower-case letters of the English alphabet ('a'-'z') is given. We would like to choose a non-empty contiguous (i.e. one-piece) fragment of the word so as to maximise the difference in the number of occurrences of the most and the least frequent letter in the fragment. We are assuming that the least frequent letter has to occur at least once in the resulting fragment. In particular, should the fragment contain occurrences of only one letter, then the most and the least frequent letter in it coincide.

已知一个长度为n的由小写字母组成的字符串,求其中连续的一段,满足该段中出现最多的字母出现的个数减去该段中出现最少的字母出现的个数最大。求这个个数。

Input

The first line of the standard input holds one integer (1<=N<=1000000)() that denotes the length of the word. The second line holds a word consisting of lower-case letters of the English alphabet.

第一行,n
第二行,该字符串
1<=n<=1000000

Output

The first and only line of the standard output is to hold a single integer, equal to the maximum difference in the number of occurrences of the most and the least frequent letter that is attained in some non-empty contiguous fragment of the input word.

一行,表示结果

Sample Input

10
aabbaaabab

Sample Output

3
Explanation of the example: The fragment that attains the difference of 3 in the number of occurrences of a and b is aaaba.
————————————————————————————————————————————
这道题我们从1扫到n 每次经过一个位置 只会改变一个字母的出现次数
我们可以把

转换成

我们用s[i]表示i这个字母的出现次数  f[i][j]表示前面某一时刻s[i]-s[j]的最小值

p[i][j]表示最小值转移时候的位置 last[i]表示i上次出现的位置

这样就完美解决答案了辣2333

#include<cstdio>
#include<cstring>
#include<algorithm>
using std::max;
using std::min;
const int M=1e6+7,inf=0x3f3f3f3f;
int read(){
    int ans=0,f=1,c=getchar();
    while(c<'0'||c>'9'){if(c=='-') f=-1; c=getchar();}
    while(c>='0'&&c<='9'){ans=ans*10+(c-'0'); c=getchar();}
    return ans*f;
}
char c[M];
int ans,n,f[26][26],s[26],last[26],p[26][26];
int main(){
    n=read(); scanf("%s",c+1);
    for(int i=1;i<=n;i++){
        int now=c[i]-'a';
        s[now]++; last[now]=i;
        for(int j=0;j<26;j++){
            if(j!=now&&s[j]) ans=max(ans,(s[now]-s[j])-f[now][j]-(p[now][j]==last[j]));
            if(j!=now&&s[j]) ans=max(ans,(s[j]-s[now])-f[j][now]-(p[j][now]==last[now]));
        }
        for(int j=0;j<26;j++){
            if(f[j][now]>s[j]-s[now]) f[j][now]=s[j]-s[now],p[j][now]=i;
            if(f[now][j]>s[now]-s[j]) f[now][j]=s[now]-s[j],p[now][j]=i;
        }
    }
    printf("%d\n",ans);
    return 0;
}
View Code

 

posted @ 2017-10-20 17:06  友人Aqwq  阅读(255)  评论(0编辑  收藏  举报