首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >codeforces 722C(带权并查集+反向思维)

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

作者头像
dejavu1zz
发布2020-10-23 15:24:24
发布2020-10-23 15:24:24
42400
代码可运行
举报
运行总次数:0
代码可运行

题意描述

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代码

代码语言:javascript
代码运行次数:0
运行
复制
#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;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/07/28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题意描述
  • 思路
  • AC代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档