【Codeforces 722 C Destroying Array】+ 并查集

来源:互联网 发布:淘宝红包在哪里领取 编辑:程序博客网 时间:2024/05/21 13:53

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

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 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.
Input

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

The second line contains n integers a1, a2, …, an (0 ≤ ai ≤ 109).

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

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

4
1 3 2 5
3 4 1 2

Output

5
4
3
0

Input

5
1 2 3 4 5
4 2 3 5 1

Output

6
5
5
1
0

Input

8
5 5 4 4 6 6 5 5
5 2 8 7 1 3 4 6

Output

18
16
11
8
8
6
6
0

Note

Consider the first sample:

Third element is destroyed. Array is now 1 3  *  5. Segment with maximum sum 5 consists of one integer 5.Fourth element is destroyed. Array is now 1 3  *   * . Segment with maximum sum 4 consists of two integers 1 3.First element is destroyed. Array is now  *  3  *   * . Segment with maximum sum 3 consists of one integer 3.Last element is destroyed. At this moment there are no valid nonempty segments left in this array, so the answer is equal to 0. 

每次删去位置为b[i]的数,最后总是全部删去,反过来就是每次加入位置为b[i]的数,若这个数左边的位置的数已加入是否可以看出一个集?右边亦是如此,更新每个集合的和是否就是正解?

AC代码:

#include<cstdio>#include<algorithm>using namespace std;typedef long long LL;const int K = 1e5 + 10;LL a[K],b[K],sum[K],cut[K],f[K],vis[K];int find(int a){   return a == f[a] ? a : f[a] = find(f[a]);}void bc(int x,int y){     int fx = find(x),fy = find(y);     if(fx != fy) f[fx] = fy,sum[fy] += sum[fx];}int main(){    int N;    scanf("%d",&N);    for(int i = 1 ; i <= N; i++) scanf("%d",&a[i]),f[i] = i;    for(int i = 1 ; i <= N; i++) scanf("%d",&b[i]);    LL ans = 0;    for(int i = N; i >= 1 ; i--){        int nl = b[i];        cut[i] = ans,vis[nl] = 1,sum[nl] = a[nl];        if(nl < N && vis[nl + 1]) bc(nl,nl + 1);        if(nl > 1 && vis[nl - 1]) bc(nl,nl - 1);        ans = max(ans,sum[find(nl)]);    }    for(int i = 1 ; i <= N; i++) printf("%lld\n",cut[i]);    return 0;}
0 0