CF EDU 1101D GCD Counting 樹形DP + 質因子分解
阿新 • • 發佈:2019-01-13
題意
有一顆樹,每個節點有一個值,問樹上最長鏈的長度,要求鏈上的每個節點的GCD值大於1。
思路
由於每個數的質因子很少,題目的資料200000<2*3*5*7*11*13*17=510510。所以每個節點的質因子個數不多。那麼樹形DP的時候直接列舉每種因子即可。
//#pragma GCC optimize(3) //#pragma comment(linker, "/STACK:102400000,102400000") //c++ // #pragma GCC diagnostic error "-std=c++11" // #pragma comment(linker, "/stack:200000000")View Code// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") #include <algorithm> #include <iterator> #include <iostream> #include <cstring> #include <cstdlib> #include <iomanip> #include <bitset> #include <cctype> #include<cstdio> #include <string> #include <vector> #include <stack> #include <cmath> #include <queue> #include <list> #include <map> #include <set> #include <cassert> using namespace std; #define lson (l , mid , rt << 1) #definerson (mid + 1 , r , rt << 1 | 1) #define debug(x) cerr << #x << " = " << x << "\n"; #define pb push_back #define pq priority_queue typedef long long ll; typedef unsigned long long ull; //typedef __int128 bll; typedef pair<ll ,ll > pll; typedef pair<int ,int > pii; typedef pair<int,pii> p3; //priority_queue<int> q;//這是一個大根堆q //priority_queue<int,vector<int>,greater<int> >q;//這是一個小根堆q #define fi first #define se second //#define endl '\n' #define OKC ios::sync_with_stdio(false);cin.tie(0) #define FT(A,B,C) for(int A=B;A <= C;++A) //用來壓行 #define REP(i , j , k) for(int i = j ; i < k ; ++i) #define max3(a,b,c) max(max(a,b), c); #define min3(a,b,c) min(min(a,b), c); //priority_queue<int ,vector<int>, greater<int> >que; const ll mos = 0x7FFFFFFF; //2147483647 const ll nmos = 0x80000000; //-2147483648 const int inf = 0x3f3f3f3f; const ll inff = 0x3f3f3f3f3f3f3f3f; //18 // const int mod = 998244353; const double esp = 1e-8; const double PI=acos(-1.0); const double PHI=0.61803399; //黃金分割點 const double tPHI=0.38196601; template<typename T> inline T read(T&x){ x=0;int f=0;char ch=getchar(); while (ch<'0'||ch>'9') f|=(ch=='-'),ch=getchar(); while (ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar(); return x=f?-x:x; } /*-----------------------showtime----------------------*/ const int maxn = 2e5+9; int a[maxn]; vector<int>mp[maxn]; int vis[maxn]; int dp[maxn]; int ans = 0; vector<int>p[maxn],t[maxn]; void dfs(int u, int fa){ for(int i=0; i<mp[u].size(); i++){ int v = mp[u][i]; if(v == fa)continue; dfs(v,u); for(int j=0; j<p[u].size(); j++){ for(int k=0; k<p[v].size(); k++){ if(p[u][j] == p[v][k]){ ans = max(ans, t[u][j] + t[v][k]); t[u][j] = max(t[u][j], t[v][k] + 1); } } } } if(a[u] > 1) ans = max(ans, 1); } int main(){ int n; scanf("%d", &n); int flag = 1; for(int i=1; i<=n; i++) { scanf("%d", &a[i]); int x = a[i]; for(ll j=2; j*j <=x; j++){ if(x%j == 0){ p[i].pb(j); t[i].pb(1); while(x%j==0) x/=j; } } if(x > 1){ p[i].pb(x); t[i].pb(1); } if(a[i] > 1) flag = 0; } if(flag) { puts("0"); return 0; } for(int i=1; i<n; i++){ int u,v; scanf("%d%d", &u, &v); mp[u].pb(v); mp[v].pb(u); } dfs(1,-1); printf("%d\n", ans); return 0; }