【UVA1205 && HDU6241】Color a Tree

洛谷

HDU

分析

贪心+并查集。

由于对于一个节点\(i\),按照贪心的策略,若\(c[i]\)最大,那么我们这一步一定是将其染色,但前提是要将其父节点染色,于是它们便有一层捆绑关系,我们可以将其看做一个节点处理。

代码

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define il inline
#define re register
#define maxn 1005
#define tie0 cin.tie(0),cout.tie(0)
#define fastio ios::sync_with_stdio(false)
#define File(x) freopen(x".in","r",stdin);freopen(x".out","w",stdout)
using namespace std;
typedef long long ll;

template <typename T> inline void read(T &x) {
    T f = 1; x = 0; char c;
    for (c = getchar(); !isdigit(c); c = getchar()) if (c == '-') f = -1;
    for ( ; isdigit(c); c = getchar()) x = x * 10 + (c ^ 48);
    x *= f;
}

int n, r;
int fa[maxn], f[maxn], c[maxn], val[maxn], times[maxn];

int find(int x) {
    return f[x] == x ? x : f[x] = find(f[x]);
}

int main() {
    while (scanf("%d%d", &n, &r) && n && r) {
        int u, v; c[0] = 0;
        memset(val, 0, sizeof(val));
        for (int i = 1; i <= n; ++i) read(c[i]);
        for (int i = 1; i < n; ++i) {
            read(u), read(v);
            fa[v] = u;
        }
        fa[r] = 0;
        for (int i = 0; i <= n; ++i) f[i] = i, times[i] = 1;
        for (int i = 1; i <= n; ++i) {
            u = 0;
            for (int j = 1; j <= n; ++j)
                if (f[j] == j && (u == 0 || c[u] * times[j] < c[j] * times[u]))
                    u = j;
            v = find(fa[u]);
            val[v] += times[v] * c[u] + val[u];
            times[v] += times[u], c[v] += c[u];
            f[u] = v;
        }
        printf("%d\n", val[0]);
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/hlw1/p/11317480.html