Codeforces 722C Destroying Array(并查集)

来源:互联网 发布:尚学堂oa源码 编辑:程序博客网 时间:2024/05/21 11:27

C. Destroying Array
time limit per test
1 second
memory limit per test
256 megabytes

You are given an array consisting of n non-negative integers a1, a2, ..., an.

You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from1 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.

Input

The first line of the input contains a single integern (1 ≤ n ≤ 100 000) — the length of the array.

The second line contains n integersa1, a2, ..., an (0 ≤ ai ≤ 109).

The third line contains a permutation of integers from1 to n — the order used to destroy elements.

Output

Print n lines. Thei-th line should contain a single integer — the maximum possible sum of elements on the segment containing no destroyed elements, after firsti operations are performed.

Examples
Input
41 3 2 53 4 1 2
Output
5430
Input
51 2 3 4 54 2 3 5 1
Output
65510
Input
85 5 4 4 6 6 5 55 2 8 7 1 3 4 6
Output
18161188660

题意:给出n个非负数,再给出n个位置,从第一个位置开始,依次删除这个位置上的数,每删除一个数,求该n个数最大连续子序列和

思路;用并查集,逆向来做,每次添加一个数,只有可能把他左边或右边的那两个数连接起来,所以用一个标记来判断相邻的两个数是否在之前已被添加,如果被添加,用并查集把这两个点合并,然后更新最大值。

#include<iostream>#include<cstdio>#include<algorithm>using namespace std;typedef long long ll;const int MAXN = 1e5+100;ll sum[MAXN],ans[MAXN],a[MAXN];int pos[MAXN],pre[MAXN];bool have[MAXN];int find(int x){if(pre[x]==x){return pre[x];}else{pre[x]=find(pre[x]);return pre[x];}}int main(void){int n;scanf("%d",&n);for(int i=1;i<=n;i++){scanf("%I64d",&a[i]);}for(int i=1;i<=n;i++){scanf("%d",&pos[i]);}for(int i=1;i<=n;i++){pre[i]=i;}ans[n]=0;for(int i=n;i>1;i--){int p=pos[i];sum[p]=a[p];if(have[p-1]){int p1=find(p),p2=find(p-1);pre[p1]=p2;sum[p2]+=sum[p1];}if(have[p+1]){int p1=find(p),p2=find(p+1);pre[p1]=p2;sum[p2]+=sum[p1];}have[p]=1;ans[i-1]=max(ans[i],sum[find(p)]);}for(int i=1;i<=n;i++){printf("%I64d\n",ans[i]);}return 0;}



原创粉丝点击