codeforces 722C(带权并查集+反向思维)

本文介绍了一种使用并查集数据结构解决动态最大子段和问题的算法。通过逆向思维,从后往前遍历数组,每次添加一个元素,并利用并查集维护当前未被破坏元素的最大子段和。此方法适用于需要动态更新子段和的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意描述

You are given an array consisting of n non-negative integers a 1, a 2, …, a n.

You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to n defining the order elements of the array are destroyed.

After each element is destroyed you have to find out the segment of the array, such that it contains no destroyed elements and the sum of its elements is maximum possible. The sum of elements in the empty segment is considered to be 0.

每次去掉一个数字,求剩余数字的最大子段和

思路

这道题可以反着来考虑,我们从后往前还是遍历,每次添加一个数字,使用并查集来维护子段和。

AC代码

#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#define x first
#define y second
#define PB push_back
#define mst(x,a) memset(x,a,sizeof(x))
#define all(a) begin(a),end(a)
#define rep(x,l,u) for(ll x=l;x<u;x++)
#define rrep(x,l,u) for(ll x=l;x>=u;x--)
#define IOS ios::sync_with_stdio(false);cin.tie(0);
using namespace std;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
typedef pair<long,long> PLL;
typedef pair<char,char> PCC;
typedef long long ll;
const int N=1e5+10;
const int M=150;
const int INF=0x3f3f3f3f;
const int MOD=998244353;
ll a[N],b[N],ans[N],w[N];
bool used[N];
struct DSU{
    vector<int> data;

    void init(int n){data.assign(n,-1);}

    bool unionSet(int x,int y){
        x=root(x);
        y=root(y);
        if(x!=y){
            //if(data[y] < data[x]) swap(x,y);//使用带权并查集时注释掉
            data[x]+=data[y];
            data[y]=x;
        }
        return x != y;
    }

    bool same(int x,int y) {return root(x)==root(y);}

    int root(int x) {return data[x] < 0 ? x : data[x]=root(data[x]);}

    int Size(int x) {return -data[root(x)];}
};
void solve(){
    mst(used,false);
    int n;cin>>n;
    DSU d;
    d.init(n+5);
    rep(i,1,n+1) cin>>a[i];
    rep(i,1,n+1) cin>>b[i];
    ans[n]=0;
    rrep(i,n,2){
        int pos=b[i];
        w[pos]=a[pos];//带权并查集
        if(used[pos-1]){//前面有数就合并
            int x=d.root(pos);
            int y=d.root(pos-1);
            d.unionSet(y,x);
            w[y]+=w[x];//权值相加
        }
        if(used[pos+1]){//后面有数就合并
            int x=d.root(pos);
            int y=d.root(pos+1);
            d.unionSet(y,x);
            w[y]+=w[x];//权值相加
        }
        used[pos]=true;
        ans[i-1]=max(ans[i],w[d.root(pos)]);//求max
    }
    rep(i,1,n+1) cout<<ans[i]<<endl;
}
int main(){
    IOS;
    solve();
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值