Codeforces Round #430 (Div. 2) C. Ilya And The Tree 树dp 统计

地址

http://codeforces.com/contest/842/problem/C

题意

给一颗树,树上每个点都有一个权值,一个节点的beauty是这个点到根节点所有权值去掉一个值(或者一个值都不去掉)的gcd,求每个节点的最大beauty

思路

考虑树dp的方法,一个节点的最大beauty要么是不算自己的权值计算出的gcd(这个可以通过dfs轻易维护出),要么是算了自己的权值计算出的gcd,如果算自己的权值,那么这个gcd一定是这个权值的某个因数,用logn的预处理枚举这个权值的所有因数,只要这个因数出现了d(d是层数,默认根节点是第0层)次以上,那么这个数可以作为beauty值,维护其最大值就好。

代码

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

#define PB push_back
#define ll rt << 1
#define rr rt << 1 | 1
#define lson l, mid, ll
#define rson mid + 1, r, rr
template<class T1, class T2> inline void gmax(T1 &a, T2 b) { if (a < b) a = b; }

typedef long long LL;
const int N = 2e5 + 5;

int n;
int a[N], b[N], cnt[N];
int head[N], enxt[N << 1], ev[N << 1], en;
vector<int> factors[N];

void dfs(int u, int fa, int d, int g) {
  b[u] = g;
  for (int factor: factors[a[u]]) if (++cnt[factor] >= d) gmax(b[u], factor);
  g = __gcd(g, a[u]);
  for (int i = head[u]; ~i; i = enxt[i]) {
    if (ev[i] == fa) continue;
    dfs(ev[i], u, d + 1, g);
  }
  for (int factor: factors[a[u]]) --cnt[factor];
}

int main() {
  for (int i = 1; i < N; ++i) for (int j = i; j < N; j += i) factors[j].PB(i);
  while (~scanf("%d", &n)) {
    for (int i = 1; i <= n; ++i) {
      scanf("%d", a + i);
      head[i] = -1;
    }
    int u, v;
    for (int i = 1; i < n; ++i) {
      scanf("%d%d", &u, &v);
      ev[en] = v; enxt[en] = head[u]; head[u] = en++;
      ev[en] = u; enxt[en] = head[v]; head[v] = en++;
    }
    dfs(1, 0, 0, 0);
    b[1] = a[1];
    for (int i = 1; i <= n; ++i) {
      printf("%d%c", b[i], i == n ? '\n' : ' ');
    }
    en = 0;
  }
}


/*
5
7 9 3 3 7
1 2
1 3
2 4
2 5

*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值