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

 

转载于:https://www.cnblogs.com/lyzuikeai/p/7700414.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值