第1行:整数n(1 ≤ n ≤ 100000),表示点的个数。 第2~n行:每行两个整数x,y表示xy之间有边,数据保证给出的是一棵树。 第n+1行:n个整数,依次表示点1~n对应的权值(1 ≤ 权值 ≤ 1,000,000,000)。
满足最长路径的长度
4 1 2 1 3 2 4 6 4 5 2
3
int gcd(int a, int b){ if (b == 0) { return a; } return gcd(b, a % b); }
bool gcdForVecNot1(vector<int>vec){ if (vec.size() < 2) { return true; } sort(vec.begin(), vec.end()); int res = gcd(vec[0], vec[1]); if (res == 1) { return false; } for (int i = 2; i < vec.size();i++) { res = gcd(vec[i], res); if (res == 1) { return false; } } return true; }
vector<int> TravelCanReach(vector<vector<int>> &vec,vector<int> &weight, int i){ vector<int> res; for (int j = 0; j < weight.size();j++) { if (weight[j] > 0 && vec[i][j] > 0) { res.push_back(j); } } return res; }
void dfs(vector<vector<int>> &vec,vector<int> &weight, vector<int> &num, int i){ if (gcdForVecNot1(num)) { if (num.size() > MaxL) { MaxL = num.size(); } vector<int> tmp = TravelCanReach(vec, weight, i); if (!tmp.empty()) { for (int j = 0; j < tmp.size();j++) { num.push_back(weight[tmp[j]]); int t = weight[tmp[j]]; weight[tmp[j]] = 0; dfs(vec, weight, num, tmp[j]); num.pop_back(); weight[tmp[j]] = t; } } } }
#include "bits/stdc++.h" using namespace std; int MaxL; int gcd(int a, int b){ if (b == 0) { return a; } return gcd(b, a % b); } bool gcdForVecNot1(vector<int>vec){ if (vec.size() < 2) { return true; } sort(vec.begin(), vec.end()); int res = gcd(vec[0], vec[1]); if (res == 1) { return false; } for (int i = 2; i < vec.size();i++) { res = gcd(vec[i], res); if (res == 1) { return false; } } return true; } vector<int> TravelCanReach(vector<vector<int>> &vec,vector<int> &weight, int i){ vector<int> res; for (int j = 0; j < weight.size();j++) { if (weight[j] > 0 && vec[i][j] > 0) { res.push_back(j); } } return res; } void dfs(vector<vector<int>> &vec,vector<int> &weight, vector<int> &num, int i){ if (gcdForVecNot1(num)) { if (num.size() > MaxL) { MaxL = num.size(); } vector<int> tmp = TravelCanReach(vec, weight, i); if (!tmp.empty()) { for (int j = 0; j < tmp.size();j++) { num.push_back(weight[tmp[j]]); int t = weight[tmp[j]]; weight[tmp[j]] = 0; dfs(vec, weight, num, tmp[j]); num.pop_back(); weight[tmp[j]] = t; } } } } int main(){ int n; while (cin >> n) { MaxL = 1; vector<vector<int>> vec(n, vector<int>(n, 0)); for (int i = 0; i < n - 1; i++) { int a, b; cin >> a >> b; vec[a - 1][b - 1] = 1; vec[b - 1][a - 1] = 1; } vector<int> weight(n, 0); for (int i = 0; i < n; i++) { cin >> weight[i]; } vector<int> num; for (int i = 0; i < n; i++) { num.push_back(weight[i]); int t = weight[i]; weight[i] = 0; dfs(vec, weight, num, i); num.pop_back(); weight[i] = t; } cout << MaxL << endl; } return 0; }