Codeforces Round #588 (Div. 2) E. Kamil and Making a Stream(DFS)
链接:
https://codeforces.com/contest/1230/problem/E
题意:
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached 100 million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?
You're given a tree — a connected undirected graph consisting of n vertices connected by n−1 edges. The tree is rooted at vertex 1. A vertex u is called an ancestor of v if it lies on the shortest path between the root and v. In particular, a vertex is an ancestor of itself.
Each vertex v is assigned its beauty xv — a non-negative integer not larger than 1012. This allows us to define the beauty of a path. Let u be an ancestor of v. Then we define the beauty f(u,v) as the greatest common divisor of the beauties of all vertices on the shortest path between u and v. Formally, if u=t1,t2,t3,…,tk=v are the vertices on the shortest path between u and v, then f(u,v)=gcd(xt1,xt2,…,xtk). Here, gcd denotes the greatest common divisor of a set of numbers. In particular, f(u,u)=gcd(xu)=xu.
Your task is to find the sum
∑u is an ancestor of vf(u,v).
As the result might be too large, please output it modulo 109+7.
Note that for each y, gcd(0,y)=gcd(y,0)=y. In particular, gcd(0,0)=0.
思路:
暴力题..map记录每个点有多少个gcd的值, 从父节点继承下来.
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int MAXN = 1e5+10;
const int MOD = 1e9+7;
LL a[MAXN], ans = 0;
vector<int> G[MAXN];
unordered_map<LL, int> Mp[MAXN];
int n;
void Dfs(int u, int fa)
{
for (auto it: Mp[fa])
{
LL gcd = __gcd(a[u], it.first);
Mp[u][gcd] += it.second;
}
Mp[u][a[u]]++;
for (auto it: Mp[u])
ans = (ans + (it.first*it.second)%MOD)%MOD;
for (auto x: G[u])
{
if (x == fa)
continue;
Dfs(x, u);
}
}
int main()
{
cin >> n;
for (int i = 1;i <= n;i++)
cin >> a[i];
int u, v;
for (int i = 1;i < n;i++)
{
cin >> u >> v;
G[u].push_back(v);
G[v].push_back(u);
}
Dfs(1, 0);
cout << ans << endl;
return 0;
}
最新文章
- 系统定位在iOS8中的改变
- entity
- [办公自动化]一次制作、多场合多次使用的PPT
- SharePoint 2016 Beta 2 使用体验
- Java关键字final、static使用总结(转)
- [课程相关]homework-08
- 在多线程中进行UI操作
- GDI+简单现实文字旋转
- HDU 1505 City Game(01矩阵 dp)
- poj1094-Sorting It All Out-拓扑排序
- Python练习六
- phpcms 自定义方法
- bash的基础特性
- JAVA代码覆盖率工具JaCoCo-原理篇
- 画线函数Glib_Line算法的研究
- C#获取文件版本信息
- list异常
- Rest分享
- Python基础:字符串的常见操作
- js处理时间的那些事