Luogu 3237 [HNOI2014]米特运输

BZOJ 3573

发现当一个点的权值确定了,整棵树的权值也会随之确定,这个确定关系表现在根结点的总权值上,如果一个点$x$的权值为$v$,那么一步步向上跳后,到根节点的权值就会变成$x*$每一个点的儿子个数。

换句话说,只要这个权值表现在根结点上的相同,那么这些点就不用修改可以构成题目要求的关系,然后我们把这个权值算出来就可以知道这样的点最多有几个了。

但是这个值太大了$long long$存不下……然后把它取一下对数(也可以哈希),就从乘法变成了加法……

时间复杂度$O(nlogn)$,如果哈希的话可以做到$O(n)$吧。

Code:

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
typedef double db;

const int N = 5e5 + 5;
const db eps = 1e-8;

int n, tot = 0, head[N], a[N], deg[N];
db f[N];

struct Edge {
    int to, nxt;
} e[N << 1];

inline void add(int from, int to) {
    e[++tot].to = to;
    e[tot].nxt = head[from];
    head[from] = tot;
}

inline void read(int &X) {
    X = 0; char ch = 0; int op = 1;
    for(; ch > '9' || ch < '0'; ch = getchar())
        if(ch == '-') op = -1;
    for(; ch >= '0' && ch <= '9'; ch = getchar())
        X = (X << 3) + (X << 1) + ch - 48;
    X *= op;
}

inline void chkMax(int &x, int y) {
    if(y > x) x = y;
}

void dfs(int x, int fat, db sum) {
    f[x] = log(a[x]) + sum;
    for(int i = head[x]; i; i = e[i].nxt) {
        int y = e[i].to;
        if(y == fat) continue;
        dfs(y, x, sum + log(deg[x] - ((x == 1) ? 0 : 1)));
    }
}

int main() {
    read(n);
    for(int i = 1; i <= n; i++) read(a[i]);
    for(int x, y, i = 1; i < n; i++) {
        read(x), read(y);
        add(x, y), add(y, x);
        ++deg[x], ++deg[y];
    }
    dfs(1, 0, 0.0);
    
    sort(f + 1, f + 1 + n);
    int cnt = 0, ans = 0;
    for(int i = 1; i <= n; i++) {
        if(f[i] - f[i - 1] <= eps) {
            ++cnt;
        } else {
            chkMax(ans, cnt);
            cnt = 1;
        }
    }
    chkMax(ans, cnt);
    
    printf("%d
", n - ans);
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/CzxingcHen/p/9901497.html