HDU 6133 Army Formations

官方题解:BestCoder Blog| 2017 Multi-University Training Contest 8 solutions BY 南京大学
这里写图片描述这里写图片描述

代码:

#include<bits/stdc++.h>
using namespace std;

#define fi first
#define se second
#define pb push_back
#define CLR(A, X) memset(A, X, sizeof(A))
#pragma comment(linker, "/STACK:102400000, 102400000")
typedef long long LL;
typedef pair<int, int> PII;
const int N = 1e5+5;

int M, b[N], lson[N], rson[N], sz[N];
LL set_sum, cnt_c[N], sum_c[N], ans[N];
PII a[N];
vector<int> G[N];

int lowbit(int x) { return x&-x; }
void add(LL *c, int x, LL d) { while(x <= M) { c[x] += d; x += lowbit(x); } }
LL sum(LL *c, int x) { LL ret = 0; while(x > 0) { ret += c[x]; x -= lowbit(x); } return ret; }

void Insert(PII x) {
    set_sum += (sum(cnt_c, M)-sum(cnt_c, x.se)+1)*x.fi;
    set_sum += sum(sum_c, x.se);
    add(cnt_c, x.se, 1);
    add(sum_c, x.se, x.fi);
}

void Sub(PII x) {
    add(cnt_c, x.se, -1);
    add(sum_c, x.se, -x.fi);
    set_sum -= (sum(cnt_c, M)-sum(cnt_c, x.se)+1)*x.fi;
    set_sum -= sum(sum_c, x.se);
}

void recover(int u) { if(u == -1) return; Insert(a[u]); recover(lson[u]); recover(rson[u]); }

void Clear(int u) { if(u == -1) return; Sub(a[u]); Clear(lson[u]); Clear(rson[u]); }

void Swap(int u, int fa) {
    lson[u] = rson[u] = -1;
    sz[u] = 1;
    for(int v:G[u]) if(v != fa) {
        if(~rson[u]) lson[u] = v;
        else rson[u] = v;
        Swap(v, u);
        sz[u] += sz[v];
    }
    if(~lson[u] && ~rson[u] && sz[lson[u]]>sz[rson[u]]) swap(lson[u], rson[u]);
}

void solve(int u) {
    if(~lson[u]) solve(lson[u]);
    if(~rson[u]) {
        Clear(lson[u]);
        solve(rson[u]);
        recover(lson[u]);
    }
    Insert(a[u]);
    ans[u] = set_sum;
}

void init(int n) {
    set_sum = 0;
    for(int i = 1; i <= n; i++) G[i].clear();
    sort(b+1, b+n+1);
    M = unique(b+1, b+n+1)-(b+1);
    for(int i = 1; i <= n; i++) {
        a[i].se = lower_bound(b+1, b+M+1, a[i].fi)-b;
        cnt_c[i] = sum_c[i] = 0;
    }
}

int main() {
    int T;
    scanf("%d", &T);
    while(T--) {
        int n, u, v;
        scanf("%d", &n);
        for(int i = 1; i <= n; i++) {
            scanf("%d", &b[i]);
            a[i].fi = b[i];
        }
        init(n);
        for(int i = 1; i < n; i++) {
            scanf("%d%d", &u, &v);
            G[u].pb(v); G[v].pb(u);
        }
        Swap(1, -1);
        solve(1);
        for(int i = 1; i <= n; i++) printf("%lld ", ans[i]);
        puts("");
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值