概述
题目连接:http://codeforces.com/contest/990/problem/G
题目描述:
You are given a tree consisting of nn vertices. A number is written on each vertex; the number on vertex ii is equal to aiai.
Let's denote the function g(x,y)g(x,y) as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex xx to vertex yy (including these two vertices).
For every integer from 11 to 2⋅1052⋅105 you have to count the number of pairs (x,y)(x,y) (1≤x≤y≤n)(1≤x≤y≤n) such that g(x,y)g(x,y) is equal to this number.
The first line contains one integer nn — the number of vertices (1≤n≤2⋅105)(1≤n≤2⋅105).
The second line contains nn integers a1a1, a2a2, ..., anan (1≤ai≤2⋅105)(1≤ai≤2⋅105) — the numbers written on vertices.
Then n−1n−1 lines follow, each containing two integers xx and yy (1≤x,y≤n,x≠y)(1≤x,y≤n,x≠y) denoting an edge connecting vertex xx with vertex yy. It is guaranteed that these edges form a tree.
For every integer ii from 11 to 2⋅1052⋅105 do the following: if there is no pair (x,y)(x,y) such that x≤yx≤y and g(x,y)=ig(x,y)=i, don't output anything. Otherwise output two integers: ii and the number of aforementioned pairs. You have to consider the values of ii in ascending order.
See the examples for better understanding.
3 1 2 3 1 2 2 3
1 4 2 1 3 1
6 1 2 4 8 16 32 1 6 6 3 3 4 4 2 6 5
1 6 2 5 4 6 8 1 16 2 32 1
4 9 16 144 6 1 3 2 3 4 3
1 1 2 1 3 1 6 2 9 2 16 2 144 1
题解:由于2e5内gcd不会有太多种,所以直接暴力回溯。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 2e5 + 7;
int val[maxn];
ll cnt[maxn];
vector<int>g[maxn];
map<int, ll> c[maxn];
void dfs(int u, int p = 0)
{
c[u][val[u]] ++;
for(int v : g[u]) {
if(v != p) {
dfs(v, u);
for(auto itu : c[u]) {
for(auto itv : c[v]) {
cnt[__gcd(itu.first, itv.first)] += itu.second * itv.second; //先统计个数
}
}
for(auto itv : c[v]) {
c[u][__gcd(val[u], itv.first)] += itv.second; //在进行更新.
}
c[v].clear(); //must clear, or it will be MLE
}
}
}
int main()
{
ios::sync_with_stdio(false), cin.tie(0);
int n;
cin >> n;
for(int i = 1;i <= n;i ++) {
cin >> val[i];
cnt[val[i]] ++;
}
for(int i = 1;i < n;i ++) {
int a, b;
cin >> a >> b;
g[a].push_back(b);
g[b].push_back(a);
}
dfs(1);
for(int i = 1;i < maxn;i ++) {
if(cnt[i]) cout << i << ' ' << cnt[i] << 'n';
}
return 0;
}
最后
以上就是眼睛大白羊为你收集整理的Codeforces 990G. GCD Counting的全部内容,希望文章能够帮你解决Codeforces 990G. GCD Counting所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复