Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define IO ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0)
- using namespace std;
- int n, LCM = 1, fact_cnt, glob_msk, ans = INT_MAX;
- vector<int> a, a_mask;
- vector<vector<int>> g, dp;
- int lcm(int a, int b)
- {
- return a / __gcd(a, b) * b;
- }
- vector<int> factorize(int x)
- {
- vector<int> ret;
- for (int i = 2; 1ll * i * i <= x; i++)
- {
- if (x % i)
- continue;
- ret.push_back(1);
- while (x % i == 0)
- {
- x /= i;
- ret.back() *= i;
- }
- }
- if (x > 1)
- {
- ret.push_back(x);
- }
- return ret;
- }
- void dfs(int u, int p)
- {
- dp[u][0] = dp[u][a_mask[u]] = 1;
- for (auto v : g[u])
- {
- if (v == p)
- continue;
- dfs(v, u);
- for (int i = 0; i <= glob_msk; i++)
- for (int j = 0; j <= glob_msk; j++)
- {
- dp[u][i | j] = min(dp[u][i | j], dp[u][i] + dp[v][j]);
- }
- }
- }
- bool test(int testnum)
- {
- string in = "test-data/";
- if (testnum < 10)
- in += "0";
- in += to_string(testnum);
- in += ".in";
- string out = "test-data/";
- if (testnum < 10)
- out += "0";
- out += to_string(testnum);
- out += ".ok";
- fstream myfile(out.c_str(), std::ios_base::in);
- // freopen(out.c_str(), "r", stdin);
- freopen(in.c_str(), "r", stdin);
- cin >> n;
- a.resize(n + 1);
- a_mask.resize(n + 1);
- g.resize(n + 1);
- for (int i = 1; i <= n; i++)
- {
- cin >> a[i];
- LCM = lcm(LCM, a[i]);
- }
- vector<int> fact = factorize(LCM);
- fact_cnt = fact.size();
- for (int i = 1; i <= n; i++)
- {
- int msk = 0;
- for (int j = 0; j < fact_cnt; j++)
- {
- if (a[i] % fact[j] == 0)
- {
- msk |= (1 << j);
- }
- }
- a_mask[i] = msk;
- }
- for (int i = 1; i < n; i++)
- {
- int u, v;
- cin >> u >> v;
- g[u].push_back(v);
- g[v].push_back(u);
- }
- bool yes = 0;
- for (int i = 1; i <= n; i++)
- {
- for (auto j : g[i])
- {
- if (lcm(a[i], a[j]) == LCM) yes = 1;
- }
- }
- glob_msk = (1 << fact_cnt) - 1;
- dp = vector<vector<int>>(n + 1, vector<int>(glob_msk + 1, n));
- dfs(1, -1);
- for (int i = 1; i <= n; i++)
- {
- ans = min(ans, dp[i][glob_msk]);
- }
- int judge_ans;
- myfile >> judge_ans;
- if (ans != judge_ans)
- {
- cout << ans << ' ' << judge_ans << ' ' << yes << '\n';
- return 0;
- }
- return 1;
- }
- int main()
- {
- IO;
- clock_t start, end;
- // Recording the end clock tick.
- // Calculating total time taken by the program.
- for (int i = 15; i <= 15; i++)
- {
- start = clock();
- cout << "test " << i << " ";
- if (test(i))
- cout << " ok\n";
- else
- cout << " WA\n";
- end = clock();
- double time_taken = double(end - start) / double(CLOCKS_PER_SEC);
- cout << "Time taken by program is : " << fixed
- << time_taken << setprecision(5);
- cout << " sec " << endl;
- }
- return 0;
- }
- // 8 11 12 15
Advertisement
Add Comment
Please, Sign In to add comment