zoukankan      html  css  js  c++  java
  • Intel Code Challenge Elimination Round (Div.1 + Div.2, combined) C. Destroying Array 带权并查集

    C. Destroying Array

    题目连接:

    http://codeforces.com/contest/722/problem/C

    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

    Hint

    题意

    有n个数,然后每个数的权值是a[i],现在按照顺序去摧毁n个元素,然后每次问你最大的连通块和是多少。

    题解:

    倒着做,然后用带权并查集去维护就好了。

    代码

    #include<bits/stdc++.h>
    using namespace std;
    const int maxn = 1e5+7;
    long long fa[maxn],a[maxn],b[maxn],ans[maxn],vis[maxn],sum[maxn],n;
    int fi(int x){return fa[x]==x?x:fa[x]=fi(fa[x]);}
    void uni(int x,int y)
    {
        x=fi(x),y=fi(y);
        fa[x]=y;sum[y]+=sum[x];
    }
    int main()
    {
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
            sum[i]=a[i];
            fa[i]=i;
        }
        for(int i=1;i<=n;i++)scanf("%d",&b[i]);
        long long tmp = 0;
        for(int i=n;i>1;i--)
        {
            vis[b[i]]=1;
            if(vis[b[i]-1])uni(b[i]-1,b[i]);
            if(vis[b[i]+1])uni(b[i]+1,b[i]);
            tmp=max(sum[fi(b[i])],tmp);
            ans[i-1]=tmp;
        }
        for(int i=1;i<=n;i++)
            cout<<ans[i]<<endl;
    }
  • 相关阅读:
    Java Arrays 的基础知识
    Java 基础知识
    C
    165. 小猫爬山 (dfs)
    164. 可达性统计
    数码 美团资格赛(整数分块)
    1079 中国剩余定理(模板)
    5814: 余数之和(整数分块)
    Greedy Sequence(主席树-区间小于每个数的最大值)
    XKC's basketball team(单调栈+二分)
  • 原文地址:https://www.cnblogs.com/qscqesze/p/5927547.html
Copyright © 2011-2022 走看看