BZOJ 3727: PA2014 Final Zadanie

Description

吉丽YY了一道神题,题面是这样的:

“一棵n个点的树,每条边长度为1,第i个结点居住着a[i]个人。假设在i结点举行会议,所有人都从原住址沿着最短路径来到i结点,行走的总路程为b[i]。输出所有b[i]。”

吉丽已经造好了数据,但熊孩子把输入文件中所有a[i]给删掉了。你能帮他恢复吗?

Input

第一行一个整数n(2<=n<=300000)。

接下来n-1行,每行两个整数x,y,表示x和y之间有连边。

接下来一行由空格隔开的n个整数bi

Output

输出一行由空格隔开的n个整数a[i]。

如果你觉得有多组解就任意输出其中一组。

Sample Input

2

1 2

17 31

Sample Output

31 17

Solution

关键是考虑到sum1不依靠a1啊啊啊。。。这样n个变量n个方程就能搞出来sum1啦!

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
typedef double DBL;
const int INF = 1009999999;
int getint() {
    int r = 0, k = 1; char c = getchar();
    for (; '0' > c || c > '9'; c = getchar()) if (c == '-') k = -1;
    for (; '0' <= c && c <= '9'; c = getchar()) r = r * 10 - '0' + c;
    return r * k;
}
const int maxn = 300005;
struct edge_type {
    int to, next;
} edge[maxn << 1];
int h[maxn], cnte = 1;
void ins(int x, int y) {
    edge[++cnte].to = y;
    edge[cnte].next = h[x];
    h[x] = cnte;
}
struct HSK {
    DBL k, b;
    HSK(DBL kk, DBL bb) { k = kk; b = bb; }
    HSK() { k = b = 0; }
    void operator += (HSK y) {
        this->k += y.k;
        this->b += y.b;
        return;
    }
    void operator -= (HSK y) {
        this->k -= y.k;
        this->b -= y.b;
        return;
    }
    HSK operator * (double y) {
        return HSK(k * y, b * y);
    }
} A[maxn], C[maxn], S;
DBL B[maxn], D[maxn], Ans[maxn];
int dis[maxn];
void dfs(int now, int father, int ndis) {
    A[now] = C[now] = HSK(DBL(0.5), DBL(B[father] - B[now]) / DBL(2.0));
    dis[now] = ndis;
    for (int i = h[now]; i; i = edge[i].next) {
        if (edge[i].to == father) continue;
        dfs(edge[i].to, now, ndis + 1);
        A[now] -= C[edge[i].to];
    }
    S += A[now] * ndis;
}
double dfs(int now, int father) {
    Ans[now] = D[now] = (B[father] - B[now] + D[1]) / DBL(2);
    for (int i = h[now]; i; i = edge[i].next) {
        if (edge[i].to == father) continue;
        Ans[now] -= dfs(edge[i].to, now);
    }
    return D[now];
}
int n;
int main() {
    n = getint();
    int x, y;
    for (int i = 1; i < n; ++i) {
        x = getint(); y = getint();
        ins(x, y); ins(y, x);
    }
    for (int i = 1; i <= n; ++i)
        B[i] = getint();
    for (int i = h[1]; i; i = edge[i].next)
        dfs(edge[i].to, 1, 1);
    Ans[1] = D[1] = (B[1] - S.b) / S.k;
    for (int i = h[1]; i; i = edge[i].next)
        Ans[1] -= dfs(edge[i].to, 1);
    for (int i = 1; i < n; ++i)
        printf("%d ", int(Ans[i] + 0.2));
    printf("%d", int(Ans[n] + 0.2));
    return 0;
}