首页 > 代码库 > CodeForces 722C Destroying Array

CodeForces 722C Destroying Array

并查集,离线操作。

将操作倒着进行,一开始所有数字都没有加入到数组中,然后倒着一个一个加入,更新最大值。

#pragma comment(linker, "/STACK:1024000000,1024000000")#include<cstdio>#include<cstring>#include<cmath>#include<algorithm>#include<vector>#include<map>#include<set>#include<queue>#include<stack>#include<iostream>using namespace std;typedef long long LL;const double pi=acos(-1.0),eps=1e-6;void File(){    freopen("D:\\in.txt","r",stdin);    freopen("D:\\out.txt","w",stdout);}template <class T>inline void read(T &x){    char c = getchar();    x = 0;    while(!isdigit(c)) c = getchar();    while(isdigit(c)) { x = x * 10 + c - 0; c = getchar(); }}const int maxn=100010;int n;LL a[maxn],sum[maxn],ans[maxn];int b[maxn],f[maxn],fa[maxn];int Find(int x){    if(x!=fa[x]) fa[x]=Find(fa[x]);    return fa[x];}void work(int a,int b){    if(b<=0||b>n) return;    if(f[b]==0) return;    int ga=Find(a),gb=Find(b);    if(ga!=gb)    {        fa[gb]=ga;        sum[ga]=sum[ga]+sum[gb];        sum[gb]=0;    }}int main(){    scanf("%d",&n);    for(int i=1;i<=n;i++) fa[i]=i;    for(int i=1;i<=n;i++) cin>>a[i];    for(int i=1;i<=n;i++) cin>>b[i];    for(int i=1;i<=n;i++) sum[i]=a[i];    LL mx=0;    for(int i=n;i>=1;i--)    {        ans[i]=mx; f[b[i]]=1;        work(b[i],b[i]-1);        work(b[i],b[i]+1);        mx=max(mx,sum[b[i]]);    }    for(int i=1;i<=n;i++) cout<<ans[i]<<endl;    return 0;}

 

CodeForces 722C Destroying Array