Destroying Array

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
inputCopy
4
1 3 2 5
3 4 1 2
outputCopy
5
4
3
0
inputCopy
5
1 2 3 4 5
4 2 3 5 1
outputCopy
6
5
5
1
0
inputCopy
8
5 5 4 4 6 6 5 5
5 2 8 7 1 3 4 6
outputCopy
18
16
11
8
8
6
6
0


直接时光倒流,用并查集每次向左右合并即可。


AC代码:

#pragma GCC optimize(2)
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e5+10;
int n,a[N],s[N],b[N],res[N],f[N],ans,flag[N];
int find(int x){return x==f[x]?x:f[x]=find(f[x]);}
signed main(){
	ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
	cin>>n;
	for(int i=1;i<=n;i++)	cin>>a[i],f[i]=i;
	for(int i=1;i<=n;i++)	cin>>b[i];
	for(int i=n;i>=1;i--){
		s[b[i]]=a[b[i]]; flag[b[i]]=1;
		if(flag[b[i]-1]){
			int x=find(b[i]),y=find(b[i]-1);
			f[y]=x,s[x]+=s[y];
		}		
		if(flag[b[i]+1]){
			int x=find(b[i]),y=find(b[i]+1);
			f[x]=y,s[y]+=s[x];
		}
		res[i-1]=max(res[i],s[find(b[i])]);
	}
	for(int i=1;i<=n;i++)	cout<<res[i]<<'\n';
	return 0;
}
发布了416 篇原创文章 · 获赞 228 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43826249/article/details/103731547