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;
    }
  • 相关阅读:
    Scala 学习 (八) 高级语法
    Scala 学习 (七) 并发编程模型Akka
    Scala 学习 (六) 面向对象
    Scala 学习(五) Set和HashSet
    Scala 学习(四) 集合之List
    Scala 学习(三) 集合之数组
    Scala 学习(二) 方法和函数
    datatable动态添加,及填充数据
    因为数据库正在使用,所以无法获得对数据库的独占访问权
    win2003超过最大连接数
  • 原文地址:https://www.cnblogs.com/qscqesze/p/5927547.html
Copyright © 2011-2022 走看看