我是靠谱客的博主 眼睛大白羊,最近开发中收集的这篇文章主要介绍Codeforces 990G. GCD Counting,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

题目连接:http://codeforces.com/contest/990/problem/G

题目描述:

G. GCD Counting
time limit per test
4.5 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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 21052⋅105 you have to count the number of pairs (x,y)(x,y) (1xyn)(1≤x≤y≤n) such that g(x,y)g(x,y) is equal to this number.

Input

The first line contains one integer nn — the number of vertices (1n2105)(1≤n≤2⋅105).

The second line contains nn integers a1a1a2a2, ..., anan (1ai2105)(1≤ai≤2⋅105) — the numbers written on vertices.

Then n1n−1 lines follow, each containing two integers xx and yy (1x,yn,xy)(1≤x,y≤n,x≠y) denoting an edge connecting vertex xx with vertex yy. It is guaranteed that these edges form a tree.

Output

For every integer ii from 11 to 21052⋅105 do the following: if there is no pair (x,y)(x,y) such that xyx≤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.

Examples
input
Copy
3
1 2 3
1 2
2 3
output
Copy
1 4
2 1
3 1
input
Copy
6
1 2 4 8 16 32
1 6
6 3
3 4
4 2
6 5
output
Copy
1 6
2 5
4 6
8 1
16 2
32 1
input
Copy
4
9 16 144 6
1 3
2 3
4 3
output
Copy
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所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(53)

评论列表共有 0 条评论

立即
投稿
返回
顶部