题解:P15080 [ICPC 2024 Chengdu R] Good Partitions

· · 题解

首先我们注意到,序列分成的每一个子序列都是单调不降的,所以如果有 a[i]>a[i+1](1 \le i,i+1 \le n),必须从 i 和 i+1 之间分隔开,若 a[i],a[i+1] 均属于同一个子序列,则该序列一定不满足要求。

因为整个序列要从 i 后断开,所以一定有 k*m=i(m \in N*),即 k 为 i 的因数,所以 k 为所有 i(a[i]>a[i+1],1 \le i,i+1 \le n) 的公因数。

然后又因为 1\le n,q \le 2 \times 10^5,并且 a[i] 与 a[i+1]((1 \le i,i+1 \le n)) 的关系在不断变化,我们思考如何维护他们的公因数,发现数据规模支持O(n \times \log(n)),可以简单地用线段树维护。

#include <bits/stdc++.h>
using namespace std;
const int N = 200005;
int t;
int n,q; 
int ans[N],a[N],tree[4*N];
int le(int x){return x<<1;}
int ri(int x){return x<<1|1;}
void did1(){
    for(int i=1; i<=N-5; i++){
        for(int j=i; j<=N-5; j+=i) ans[j]++;
    }
}
int gcd(int x,int y){
    if(x==0) return y;
    if(y==0) return x;
    if(x%y==0) return y;
    return gcd(y,x%y);
}
void push_up(int x){
    tree[x] = gcd(tree[le(x)],tree[ri(x)]);
}
void update(int l,int r,int now,int pos,int val){
    if(l>=r){
        tree[now] = val;
        return;
    }
    int mid = (l+r)/2;
    if(pos<=mid) update(l,mid,le(now),pos,val);
    else update(mid+1,r,ri(now),pos,val);
    push_up(now);
}
int main(){
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    cin >> t;
    did1();//初始化所有的答案
    while(t--){
        cin >> n >> q;
        ans[0] = n;//答案最大为n 
        memset(tree,0,sizeof(tree));
        for(int i=1; i<=n; i++){
            cin >> a[i];
            if(i==1) continue;
            if(a[i-1]>a[i]){
                update(1,n,1,i-1,i-1);//加入a[i]>a[i+1]的i
            }else update(1,n,1,i-1,0);//否则无限制  
        }
        cout << ans[tree[1]] << '\n';
        for(int i=1; i<=q; i++){
            int p,v;
            cin >> p >> v;
            a[p] = v;
            if(p>1&&a[p-1]>a[p]) update(1,n,1,p-1,p-1);
            else if(p>1) update(1,n,1,p-1,0);
            if(p<n&&a[p]>a[p+1]) update(1,n,1,p,p);
            else if(p<n) update(1,n,1,p,0);
            cout << ans[tree[1]] << '\n';
        }
    }
    return 0;
}