Destroying Array(并查集)CodeForces-722C

Destroying Array

Description

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.

Sample Input

4
1 3 2 5
3 4 1 2

Sample Output

5
4
3
0

分析:

直接按找题目所说的顺序去模拟似乎是困难的,因此想到用逆向思维,将逐个破坏数组元素改为逐个生成数组元素,这样就可以利用并查集将连在一起的数组元素归到一棵树上,每次生成新元素时维护各集合的最大值即可

代码:

#include <iostream>
#include <cstdio>
#define ll long long
using namespace std;
int a[100050];
int d[100050];
int vis[100050];
ll sum[100050];
int fa[100050];
ll res[100050];
int n;
int find(int x) {
	if (x > n || x <= 0) return -1;
	return x == fa[x] ? x : fa[x] = find(fa[x]);
}
int main()
{
	int i, j, temp;
	ll max = 0;
	cin >> n;
	for (i = 1; i <= n; i++) scanf("%d", &a[i]);
	for (i = n; i >= 1; i--) scanf("%d", &d[i]);
	for (i = 1; i <=n; i++) {//初始化各节点指向自己 
		fa[i] = i;
		vis[i] = 0;
		sum[i] = a[i];
	}
	for (i = 1; i < n; i++) {
		j = d[i];
		vis[j] = 1;
		int r = find(j + 1);
		int l = find(j - 1);
		if ((l == -1 || vis[l] == 0) && (r == -1 || vis[r] == 0)) {//左右两端都没有已访问的元素,不操作 
		}
		else {
			if (r != -1 && vis[r] != 0) {
				if (l == -1 || vis[l] == 0) {//只有右端有已访问的元素 
					fa[j] = r;
					sum[r] += sum[j];
				}
				else {//左右两端都有已访问元素 
					fa[l] = r;
					fa[j] = r;
					sum[r] += sum[l] + sum[j];
				}
			}
			else {//只有左端有已访问的元素
				fa[j] = l;
				sum[l] += sum[j];
			}
		}
		temp = find(j);
		if (sum[temp] > max)
			max = sum[temp];
		res[n -1- i] = max;
	}
	for (i = 0; i < n; i++)
		cout << res[i] << endl;
	return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值