codeforce 842C. Ilya And The Tree(dfs用set存储到每种可能)

来源:互联网 发布:淘宝网买家可以贷款吗 编辑:程序博客网 时间:2024/05/17 09:18

time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
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 ≤ n, 1 ≤ ai ≤ 2·105).

Each of next n - 1 lines contains two integer numbers x and y (1 ≤ x, y ≤ n, x ≠ 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

这题昨天我没读明白,我以为是能够将无限个顶点都能设置为0,后来发现是到每个点的路径中只能设置路径中的一个节点变为0,细想一下这题并没有这么难,但是昨天做的确实惨不忍睹,好像只有300多人过了,自己也是菜的一匹

思路,就是用set存储每个点的所有可能的gcd,并取其中的最大值,把每个点变为0或者不变为0的情况都放入这个点的set中,详细看代码

代码如下:

#include<bits/stdc++.h>using namespace std;const int MAX_V = 2e5+10;vector<int> G[MAX_V];set<int> st[MAX_V];set<int>::iterator it;int V,a[MAX_V];bool used[MAX_V]; void dfs(int ri,int fi,int G_CD){//G_CD代表到当前节点前,即父亲节点的每个点都使用的GCD     used[ri] = true;//每个节点只用一次     for(it = st[fi].begin();it != st[fi].end();it++){        st[ri].insert(__gcd(*it,a[ri]));//把父亲节点的所有情况都加上选择这个节点时     }    st[ri].insert(G_CD);//即不使用这个节点     G_CD = __gcd(G_CD,a[ri]);//使用这个节点     st[ri].insert(G_CD);    for(int i=0;i<G[ri].size();i++){        int x = G[ri][i];        if(!used[x])            dfs(x,ri,G_CD);    }}int main(void){    scanf("%d",&V);    for(int i=1;i<=V;i++){        scanf("%d",&a[i]);    }    int u,v;    for(int i=1;i<V;i++){        scanf("%d %d",&u,&v);        G[u].push_back(v);        G[v].push_back(u);    }    dfs(1,0,0);    for(int i=1;i<=V;i++){       printf("%d ",*st[i].rbegin());//rbegin是set里面的最大值     }    return 0;}

反向迭代器:
这里写图片描述

原创粉丝点击