# BZOJ 2213: [Poi2011]Difference

## 2213: [Poi2011]Difference

Time Limit: 10 Sec  Memory Limit: 32 MB
Submit: 481  Solved: 171
[Submit][Status][Discuss]

## 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.

## 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.

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.

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.

## 代码：

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
//by NeighThorn
using namespace std;

const int maxn=1000000+5,maxm=26+5;

int n,ans,tot[maxm],cnt[maxm][maxm],Min[2][maxm][maxm],val[2][maxm][maxm];
char str[maxn];

inline void update(int x,int y){
if(val[0][x][y]!=tot[y])
ans=max(cnt[x][y]-Min[0][x][y],ans);
else if(val[1][x][y]!=tot[y])
ans=max(cnt[x][y]-Min[1][x][y],ans);
if(cnt[x][y]<Min[0][x][y]&&val[0][x][y]!=tot[y]){
Min[1][x][y]=Min[0][x][y];
val[1][x][y]=val[0][x][y];
Min[0][x][y]=cnt[x][y];
val[0][x][y]=tot[y];
}
else if(cnt[x][y]<Min[0][x][y]){
Min[0][x][y]=cnt[x][y];
val[0][x][y]=tot[y];
}
else if(cnt[x][y]<Min[1][x][y]&&val[0][x][y]!=tot[y]){
Min[1][x][y]=cnt[x][y];
val[1][x][y]=tot[y];
}
}

signed main(void){
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
scanf("%d%s",&n,str+1);
for(int i=1,k,t;i<=n;i++)
for(k=0,t=str[i]-'a',tot[t]++;k<26;k++)
if(k!=t)
cnt[t][k]++,update(t,k),
cnt[k][t]--,update(k,t);
printf("%d\n",ans);
return 0;
}


By NeighThorn

posted @ 2017-03-20 16:36  NeighThorn  阅读(271)  评论(0编辑  收藏  举报