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 
#include 
#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;
}

你可能感兴趣的:(并查集)