这题没法用分块做吗
  • 板块P3939 数颜色
  • 楼主Calanosay
  • 当前回复20
  • 已保存回复20
  • 发布时间2021/7/21 17:02
  • 上次更新2023/11/4 13:55:59
查看原帖
这题没法用分块做吗
434015
Calanosay楼主2021/7/21 17:02
#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
const int maxn = 3e5+5;
const int maxq = 1e3;
int st[maxq],ed[maxq],sizee[maxq],bel[maxn],a[maxn];
int n,m,sq;
vector<int> g[maxq];
void updateg(int x){
    for(int i = 0;i < sizee[x];i++){
        g[x].push_back(a[st[x]+i]);
    }
    sort(g[x].begin(),g[x].end());
}
void init(){
    sq = sqrt(n);
    for (int i = 1; i <= sq; ++i) {
        st[i] = n / sq * (i - 1) + 1;
        ed[i] = n / sq * i;
    }

    ed[sq] = n;

    for (int i = 1; i <= sq; ++i) {
        for (int j = st[i]; j <= ed[i]; ++j) {
            g[i].push_back(a[j]);
            bel[j] = i;
        }
    }
    for (int i = 1; i <= sq; ++i) {
        sort(g[i].begin(),g[i].end());
        sizee[i] = ed[i] - st[i] + 1;
    }
}
void update(int x,int y){
    if(bel[x]==bel[y]){
        swap(a[x],a[y]);
    }
    else{
        swap(a[x],a[y]);
        updateg(bel[x]);
        updateg(bel[y]);
    }
}
int query(int x,int y,int k){
    int ans = 0;
    if(bel[x]==bel[y]){
        for (int i = x; i <= y; ++i) {
                if(a[i] == k) ans++;
        }
        return ans;
    }
    else{
        for (int i = x; i <= ed[bel[x]]; ++i) {
            if(a[i]==k) ans++;
        }
        for (int i = st[bel[y]]; i <= y; ++i) {
            if(a[i]==k) ans++;
        }
        for (int i = bel[x]+1; i < bel[y]; ++i) {
            ans += upper_bound(g[i].begin(),g[i].end(),k) - lower_bound(g[i].begin(),g[i].end(),k);
        }
    }
    return ans;
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    cin >> n >> m;
    for (int i = 1; i <= n; ++i) {
        cin >> a[i];
    }
    init();
    while (m--){
        int op,l,r,c;
        cin>>op;
        if(op==1){
            cin>>l>>r>>c;
            cout<<query(l,r,c)<<endl;
        }
        else{
            cin>>c;
            update(c,c+1);
        }
    }

}

分块,wa且tle,求助(另外其实对分块的时间复杂度还不是很清晰

2021/7/21 17:02
加载中...