• 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;
    }
  • 相关阅读:
    抓取登录后的数据
    Form认证的几点说明
    eclipse启动错误:java.lang.NoClassDefFoundError: org/eclipse/core/resources/IContainer
    mysql游标的使用 No data
    mysql insert 主键 重复问题
    tail 命令
    maven 打包可执行jar的方法
    maven中如何打包源代码
    工程师,请优化你的代码
    在服务器端判断request来自Ajax请求(异步)还是传统请求(同步)
  • 原文地址:https://www.cnblogs.com/qscqesze/p/5927547.html
Copyright © 2020-2023  润新知