C. Ilya And The Tree (gcd analysis of violence + transfer)

topic

Meaning of the questions:

    Given a tree, each point has the right values. gcd right answer to all points on each node to the root node equal to the value of the path, for each point, weight can make a point on this path value becomes 0, the answer requires that each node as large as possible.
     1 n 2 1 0 5 , 1 i n , 1 a i 2 1 0 5 1 ≤ n ≤ 2·10^5,1 ≤ i ≤ n, 1 ≤ a_i ≤ 2·10^5

analysis:

    Because gcd, gcd is a very obvious nature of these types of values ​​are not many, the key point of this question here. So we can violence to calculate, for each point to maintain a set, after the deposit of the current node to delete a point on the root path of the rest of the gcd. When searching maintenance of this set on it, for the current node, was taken with the right numbers to the current node's value takes gcd can be set from an array of parent nodes, since only deleted once, plus the deletion of the current node gcd can be, this gcd recursively when the next pass.

#include <iostream>
#include <vector>
#include <set> 
using namespace std;

vector<int> g[200005];
set<int> res[200005];
int dp[200005][2],v[200005];

int _gcd(int a,int b)
{
	if( b == 0 ) return a;
	return _gcd(b,a%b);
} 

void dfs(int x,int fa,int gcd)
{
	for (int i = 0; i < g[x].size(); i++)
	{
		int t = g[x][i];
		if( t == fa ) continue;
		set<int>:: iterator it;
		res[t].insert(gcd);
		for (it = res[x].begin(); it != res[x].end(); it++)
		{
			res[t].insert(_gcd(*it,v[t]));
		}
		dfs(t,x,_gcd(gcd,v[t]));
	}
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	int n;
	cin >> n;
	for (int i = 1; i <= n; i++)
	{
		cin >> v[i];
	}
	for (int i = 1; i < n; i++)
	{
		int x,y;
		cin >> x >> y;
		g[x].push_back(y);
		g[y].push_back(x);  
	}
	dp[1][0] = v[1];
	dp[1][1] = 0;
	res[1].insert(0);
	dfs(1,0,v[1]);
	for (int i = 1; i <= n; i++)
	{
		if( i == 1 ) cout << v[i];
		else cout << *--res[i].end();
		if( i == n ) cout << '\n';
		else cout << ' ';
	}
	return 0;
}

Published 132 original articles · won praise 6 · views 7908

Guess you like

Origin blog.csdn.net/weixin_44316314/article/details/105137331