codeforces 842C. Ilya And The Tree(dfs)
来源:互联网 发布:阿里域名个人备案 编辑:程序博客网 时间:2024/06/07 02:59
题意:
有n个节点标号1~n,每个节点有一个正整数价值,这几个节点形成了一棵以节点1为根节点的树,求根节点到节点x的路径上所有节点价值的gcd(你可改变这条路径上某个节点的的价值为0,或者不做任何修改);
思路:
从根节点开始,求每个节点可能的gcd,用set维护这些gcd。则每个节点的可能的gcd必包括 其父节点的gcd与当前节点的价值的最大公因数。但漏了一种情况,不修改从根节点到当前节点的根节点的任何价值,只修改当前节点的价值,所以要维护一个从根节点到当前节点的根节点的gcd。
代码:
#include <bits/stdc++.h>using namespace std;const int maxn = 2e5+7;set<int> s[maxn];int arr[maxn];vector<int> e[maxn];set<int>::iterator it;void dfs(int u,int fa,int gcd){ for(it=s[fa].begin();it!=s[fa].end();it++) s[u].insert(__gcd(*it,arr[u])); s[u].insert(gcd); gcd = __gcd(gcd,arr[u]); s[u].insert(gcd); int len = e[u].size(); for(int i = 0;i<len;i++) { int v = e[u][i]; if(v!=fa) { dfs(v,u,gcd); } }}int main(){ int n; cin>>n; for(int i = 1;i<=n;i++) scanf("%d",arr+i); for(int i = 0;i<n-1;i++) { int u,v; scanf("%d%d",&u,&v); e[u].push_back(v); e[v].push_back(u); } dfs(1,0,0); for(int i = 1;i<=n;i++) { printf("%d ",*s[i].rbegin()); } return 0;}
阅读全文
1 0
- Codeforces 842 C. Ilya And The Tree (dfs)
- Codeforces 842C Ilya And The Tree【Dfs】
- codeforces 842C. Ilya And The Tree(dfs)
- Codeforces 842 C. Ilya And The Tree (dfs)
- Codeforces 842C Ilya And The Tree
- Codeforces 842 C Ilya And The Tree
- Codeforces 842 C. Ilya And The Tree 树上dp
- Codeforces Round #430 (Div. 2) C. Ilya And The Tree(dfs)
- Codeforces Round #430 (Div. 2) C. Ilya And The Tree(dfs+最大公约数+因子+树)
- Codeforces Round #430 (Div. 2)C. Ilya And The Tree dfs D
- Codeforces Round #430(Div.2)Problem C Ilya And The Tree(DFS)
- Codeforces Round #430 (Div. 2) C. Ilya And The Tree dfs+set
- 842C Ilya And The Tree
- Codeforces Round #430 (Div. 2) C. Ilya And The Tree
- Codeforces 430 Div 2 C.Ilya And The tree
- Codeforces Round #430 (Div. 2) C. Ilya And The Tree
- codeforce 842C. Ilya And The Tree(dfs用set存储到每种可能)
- Ilya And The Tree(dfs,数学)
- UICollectionView
- 加速近端梯度法——解决非平滑优化问题
- Java编程思想之泛型(上)
- mysql状态分析之show global status
- Ubuntu更改默认python版本的两种方法 python-> Anaconda
- codeforces 842C. Ilya And The Tree(dfs)
- GC详解及Minor GC和Full GC触发条件总结
- C 的递归
- Java常考面试题
- 2017智慧树冲上云霄—飞机鉴赏答案
- 深度学习的知识点总结
- Java并发编程:volatile关键字解析
- POJ2253Frogger(最短路)
- Flask用户认证架构图