[CodeForces 1101D] GCD Counting(树形 DP) | 错题本

文章目录

题目

[CodeForces 1101D] GCD Counting

分析

a u a_u 分解质因数得到不同的质因子 p [ u ] 1 , p [ u ] 2 , , p [ u ] t p[u]_1, p[u]_2, \cdots, p[u]_t d p [ u ] [ i ] dp[u][i] 表示从 u u 向下只经过含因子 p [ u ] i p[u]_i 的数能延伸的最长距离,转移的时候暴力枚举 x , y   ( p [ u ] x = p [ v ] y ) x, y\ (p[u]_x = p[v]_y) ,将最大的两条 d p [ v 1 ] [ x ] , d p [ v 2 ] [ y ] dp[v_1][x], dp[v_2][y] 接起来,更新答案即可。注意 v 1 , v 2 v_1, v_2 也不需要枚举, v 1 v_1 在循环时动态更新, v 2 v_2 视为当前结点即可。即 a n s = max { a n s , d p [ u ] [ x ] + d p [ v ] [ y ] } d p [ u ] [ x ] = max { d p [ u ] [ x ] , d p [ v ] [ y ] + 1 } \begin{aligned} ans &= \max\{ans, dp[u][x] + dp[v][y]\} \\ dp[u][x] &= \max\{dp[u][x], dp[v][y] + 1\} \end{aligned}

当然这道题可以也可以点分治做,直接分开,递归回来过后两次循环暴力找最长的两根链接起来就是当前结点的答案。

错因

  • 开始想的是要枚举 v 1 , v 2 v_1, v_2 和它们的因数, n 4 n^4 ……看了题解发现首先不用枚举所有因数,只需要质因数,并且 v 1 v_1 也可以动态更新,确定了 v 1 v_1 v 2 v_2 也成了个 O ( n ) O(n) 的东西了。

代码

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

typedef std::pair<int, int> PII;

const int MAXN = 200000;

int N, A[MAXN + 5];
std::vector<int> G[MAXN + 5];
std::vector<PII> D[MAXN + 5];

int Ans;
int Dp[MAXN + 5][10];

void Divid(int u) {
	int tmp = A[u];
	for (int i = 2; i * i <= A[u]; i++) {
		if (tmp % i == 0) {
			int j = 0;
			while (tmp % i == 0)
				tmp /= i, j++;
			D[u].push_back(std::make_pair(i, j));
		}
	}
	if (tmp != 1)
		D[u].push_back(std::make_pair(tmp, 1));
}

void Dfs(int u, int fa) {
	Divid(u);
	for (int i = 0; i < int(D[u].size()); i++)
		Dp[u][i] = 1;
	for (int i = 0; i < int(G[u].size()); i++) {
		int v = G[u][i];
		if (v != fa) {
			Dfs(v, u);
			for (int x = 0; x < int(D[u].size()); x++)
				for (int y = 0; y < int(D[v].size()); y++)
					if (D[u][x].first == D[v][y].first) {
						Ans = std::max(Ans, Dp[u][x] + Dp[v][y]);
						Dp[u][x] = std::max(Dp[u][x], Dp[v][y] + 1);
					}
		}
	}
}

int main() {
	scanf("%d", &N);
	bool flag = true;
	for (int i = 1; i <= N; i++) {
		scanf("%d", &A[i]);
		if (A[i] != 1)
			flag = false;
	}
	if (flag)
		return printf("0"), 0;
	Ans = 1;
	for (int i = 1; i < N; i++) {
		int u, v; scanf("%d%d", &u, &v);
		G[u].push_back(v), G[v].push_back(u);
	}
	Dfs(1, 0);
	printf("%d", Ans);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/C20190102/article/details/107666420
今日推荐