bzoj2213: [Poi2011]Difference(思维题)

     今天颓了一天T T

  这题有两种写法...

  ①预处理出每种字符在原字符串中的位置,枚举两种字符作为最大值和最小值,把这两种字符的坐标归并排序,把最大值设为1,最小值设为-1,求最大子段和。注意因为最小值必须出现一次,所以要记录前缀最小值和次小值,答案只更新最小值出现次数不为0的一个,对于一个字符的出现次数用当前出现次数是否等于前缀最小值出现次数来判断就好了,复杂度O(50N)。

#include<iostream> 
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<cmath> 
#include<algorithm> 
using namespace std;
const int maxn=1000010,inf=1e9;
int n,ans,cnt;
int num[maxn],sum[maxn],last[maxn],pre[maxn],q[maxn];
char s[maxn];
inline void read(int &k)
{
    int f=1;k=0;char c=getchar();
    while(c<'0'||c>'9')c=='-'&&(f=-1),c=getchar();
    while(c<='9'&&c>='0')k=k*10+c-'0',c=getchar();
    k*=f;
}
void solve(int x,int y)
{
    int mn1=0,mn2=inf,frt1=0;
    for(int i=1;i<=cnt;i++)
    {
        num[i]=num[i-1]+(s[q[i]]-'a'==y);
        sum[i]=sum[i-1]+(s[q[i]]-'a'==x?1:-1);
        if(num[i]==frt1)mn1=min(mn1,sum[i]);
        else if(sum[i]<mn1)mn2=mn1,mn1=sum[i],frt1=num[i];
        else if(sum[i]<mn2)mn2=sum[i];
        if(num[i]-frt1>0)ans=max(ans,sum[i]-mn1);
        else ans=max(ans,sum[i]-mn2);
    }
}
int main()
{
    read(n);scanf("%s",s+1);
    for(int i=1;i<=n;i++)pre[i]=last[s[i]-'a'],last[s[i]-'a']=i;
    for(int i=0;i<26;i++)
    for(int j=0;j<i;j++)
    if(last[i]&&last[j])
    {
        cnt=0;int l1=last[i],l2=last[j];
        while(l1||l2)
        if(l1>l2)q[++cnt]=l1,l1=pre[l1];
        else q[++cnt]=l2,l2=pre[l2];
        solve(i,j);solve(j,i);
    }
    printf("%d\n",ans);
}
View Code

  ②对于两个字符计算答案为cnt[r][a]-cnt[l][a]-(cnt[r][b]-cnt[l][b]),可以转化成cnt[r][a]-cnt[r][b]和cnt[l][a]-cnt[l][b],于是我们只要记录一下当前值和前面的最小值,次小值,更新一个前缀y的数量不一样的就好了。因为每移动一格只会更新50个cnt,于是复杂度为O(50N)。

#include<iostream> 
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<cmath> 
#include<algorithm> 
using namespace std;
const int maxn=1000010,inf=1e9;
int n,ans;
int num[27][27],cnt[27],g1[27][27],g2[27][27],f[27][27];
char s[maxn];
inline void read(int &k)
{
    int f=1;k=0;char c=getchar();
    while(c<'0'||c>'9')c=='-'&&(f=-1),c=getchar();
    while(c<='9'&&c>='0')k=k*10+c-'0',c=getchar();
    k*=f;
}
void solve(int x,int y)
{
    if(num[x][y]==cnt[y])g1[x][y]=min(g1[x][y],f[x][y]);
    else if(f[x][y]<g1[x][y])g2[x][y]=g1[x][y],g1[x][y]=f[x][y],num[x][y]=cnt[y];
    else if(f[x][y]<g2[x][y])g2[x][y]=f[x][y];
    if(num[x][y]!=cnt[y])ans=max(ans,f[x][y]-g1[x][y]);
    else ans=max(ans,f[x][y]-g2[x][y]);
}
int main()
{
    read(n);scanf("%s",s+1);
    memset(g2,32,sizeof(g2));
    for(int i=1;i<=n;i++)
    {
        cnt[s[i]-'a']++;    
        for(int j=0;j<26;j++)
        if(s[i]-'a'!=j)f[s[i]-'a'][j]++,solve(s[i]-'a',j),f[j][s[i]-'a']--,solve(j,s[i]-'a');    
    } 
    printf("%d\n",ans);
}
View Code

转载于:https://www.cnblogs.com/Sakits/p/7701931.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值