题解:P14577 磁极变换

· · 题解

并没有难度,顶着个发烧的 debuff 做的慢了点 /ng

首先很容易发现每种字母都只有区间内最后一个可能生效。

抛掉各种奇奇怪怪的利用这玩意优化暴力的想法,考虑直接 check 一个位置是否可以留存。

对于每种字母求当前位置前后两个,如果在区间内配对,那么该位置就似了,否则就活下来。

配对与否可以对每个字母做前缀和,根据数量判断。

存位置下来二分可以 O(qV^2\log^2n),其中 V=26,会爆炸。

但是二分这一步其实可以预处理,对于每个位置把所有字母前面的最后一个都存下来即可。

于是做到了 O(qV^2),卡卡常可以过。

TLE 的话开快读能快一倍 /jk

#include<bits/stdc++.h>
using namespace std;
int read(){
    int sum=0,fish=1;
    char c=getchar_unlocked();
    while((c<'0'||c>'9')&&c!='-')c=getchar_unlocked();
    if(c=='-')fish=-1,c=getchar_unlocked();
    while(c>='0'&&c<='9')sum=sum*10+(c-'0'),c=getchar_unlocked();
    return sum*fish;
}
void print(long long x){
    if(x<0)putchar_unlocked('-'),x=-x;
    if(x<10)putchar_unlocked(x+'0');
    else print(x/10),putchar_unlocked(x%10+'0');
}
int a[500005];
int n;
int qzh[500005][30];
int mx[500005][30];
void solve(int l,int r){
    long long ans=0;
    for(int i=1;i<=26;i++){
        int x=mx[r][i];
        if(x<l)continue;
        if((qzh[x][i]&1)==(qzh[l-1][i]&1))continue;
        bool ret=1;
        for(int j=1;j<=26&&ret;j++){
            int y=mx[x][j];
            if(y<l)continue;
            if((qzh[y][j]-qzh[l-1][j])%2&&qzh[r][j]-qzh[y][j]>0)ret=0;
        }
        if(ret)ans+=a[x];
    }
    print(ans),puts("");
    return;
}
signed main(){
    string s;
    n=read();
    cin>>s;
    s=" "+s;
    for(int i=1;i<=n;i++){
        a[i]=read();
        for(int op=1;op<=26;op++)
        qzh[i][op]=qzh[i-1][op],mx[i][op]=mx[i-1][op];
        qzh[i][(s[i]-'a'+1)]++;
        mx[i][(s[i]-'a'+1)]=i;
    }
    int q;
    cin>>q;
    while(q--){
        int op=read();
        int x,y;
        x=read(),y=read();
        if(op==1){
            a[x]=y;
            continue;
        }
        solve(x,y);
    }
    return 0;
}
// ──你很努力了。真厉害。

// ──谢谢你来见我。

// ──但我已经不是你心里最重要的人了。

// ──你想再见一面的对象,是在这段回忆的外面吧──?