码迷,mamicode.com
首页 > 其他好文 > 详细

CF 842C Ilya And The Tree(树上DFS)

时间:2018-01-07 11:34:26      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:链接   statement   comm   1.0   cti   begin   数据类型   stl   rbegin   

题目链接:http://codeforces.com/problemset/problem/842/C

题目:

Ilya is very fond of graphs, especially trees. During his last trip to the forest Ilya found a very interesting tree rooted at vertex 1. There is an integer number written on each vertex of the tree; the number written on vertex i is equal to ai.

Ilya believes that the beauty of the vertex x is the greatest common divisor of all numbers written on the vertices on the path from the root to x, including this vertex itself. In addition, Ilya can change the number in one arbitrary vertex to 0 or leave all vertices unchanged. Now for each vertex Ilya wants to know the maximum possible beauty it can have.

For each vertex the answer must be considered independently.

The beauty of the root equals to number written on it.

Input

First line contains one integer number n — the number of vertices in tree (1 ≤ n ≤ 2·105).

Next line contains n integer numbers ai (1 ≤ i ≤ n1 ≤ ai ≤ 2·105).

Each of next n - 1 lines contains two integer numbers x and y (1 ≤ x, y ≤ nx ≠ y), which means that there is an edge (x, y) in the tree.

Output

Output n numbers separated by spaces, where i-th number equals to maximum possible beauty of vertex i.

Examples
input
2
6 2
1 2
output
6 6 
input
3
6 2 3
1 2
1 3
output
6 6 6 
input
1
10
output
10 

题意:给定一棵树,根为1。求各顶点从根到该顶点路径上所有顶点的gcd(路径上可以使其中一个顶点为0)。

题解:以集合的形式,进行操作。该点可能的答案是其父亲节点可能的答案与该点的GCD 或 使该点为0的GCD 或 整条路径上不置0的GCD。放一个集合里,然后取最大值。

从这个题目中学到好多新科技哇!

1.首先是auto,自动判断数据类型,对于STL的各种容器就很方便。

2.集合set 的rbegin()函数

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 #define PI acos(-1.0)
 5 #define INF 0x3f3f3f3f
 6 #define FAST_IO ios::sync_with_stdio(false)
 7 #define CLR(arr,val) memset(arr,val,sizeof(arr))
 8 
 9 typedef long long LL;
10 const int N=2*1e5+1000;
11 int a[N];
12 set <int> s[N];
13 vector <int> E[N];
14 
15 void DFS(int u,int Fa,int GCD){
16     for(auto i:s[Fa]) s[u].insert(__gcd(i,a[u]));
17     s[u].insert(GCD);
18     GCD=__gcd(GCD,a[u]);
19     s[u].insert(GCD);
20     for(auto i:E[u]){
21         if(i!=Fa) DFS(i,u,GCD);
22     }
23 }
24 
25 int main(){
26     int n,x,y;
27     scanf("%d",&n);
28     for(int i=1;i<=n;i++) scanf("%d",&a[i]);
29     for(int i=1;i<n;i++){
30         scanf("%d %d",&x,&y);
31         E[x].push_back(y);
32         E[y].push_back(x);
33     }
34     DFS(1,0,0);
35     for(int i=1;i<=n;i++){
36         printf("%d ",*s[i].rbegin());
37     }
38     return 0;
39 }

 

 

CF 842C Ilya And The Tree(树上DFS)

标签:链接   statement   comm   1.0   cti   begin   数据类型   stl   rbegin   

原文地址:https://www.cnblogs.com/Leonard-/p/8215812.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!