fork download
  1. // ~~ icebear ~~
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. typedef long long ll;
  6. typedef pair<int, int> ii;
  7. typedef pair<ii, int> iii;
  8.  
  9. #define FOR(i,a,b) for(int i=(a); i<=(b); ++i)
  10. #define FORR(i,a,b) for(int i=(a); i>=(b); --i)
  11. #define rep(i, n) for(int i=0; i<(n); ++i)
  12. #define red(i, n) for(int i=(n)-1; i>=0; --i)
  13. #define mp make_pair
  14. #define pb push_back
  15. #define fi first
  16. #define se second
  17. #define ar(x) array<int, (x)>
  18. #define all(x) x.begin(), x.end()
  19. #define task "icebearat"
  20.  
  21. const int MOD = 1e9 + 7;
  22. const int inf = 1e9 + 27092008;
  23. const ll LLinf = 1e18 + 27092008;
  24. const int N = 2e5 + 5;
  25. int numNode, numQuery;
  26. vector<int> G[N];
  27. int sz[N], heavy_child[N];
  28. int tin[N], tout[N], etour[N], timer = 0;
  29.  
  30. void DFS(int u, int par) {
  31. tin[u] = ++timer;
  32. etour[timer] = u;
  33. sz[u] = 1;
  34. int max_sz = 0;
  35.  
  36. for(int v : G[u])
  37. if (v != par) {
  38. DFS(v, u);
  39. sz[u] += sz[v];
  40.  
  41. if (max_sz < sz[v]) {
  42. max_sz = sz[v];
  43. heavy_child[u] = v;
  44. }
  45. }
  46. tout[u] = timer;
  47. }
  48.  
  49. map<int, int> cntDiv;
  50. ll ans = 0;
  51. int a[N];
  52.  
  53. void add(int x) { cntDiv[a[x]]++; }
  54. void del(int x) { cntDiv[a[x]]--; }
  55. void dsu_ontree(int u, int par, bool keep) {
  56. for(int v : G[u])
  57. if (v != par && v != heavy_child[u])
  58. dsu_ontree(v, u, false);
  59.  
  60. if (heavy_child[u] != 0)
  61. dsu_ontree(heavy_child[u], u, true);
  62.  
  63. ans += cntDiv[1];
  64. add(u);
  65. for(int v : G[u])
  66. if (v != par && v != heavy_child[u]) {
  67. FOR(i, tin[v], tout[v])
  68. if (a[u] % a[etour[i]] == 0)
  69. ans += cntDiv[a[u] / a[etour[i]]];
  70. FOR(i, tin[v], tout[v])
  71. add(etour[i]);
  72. }
  73.  
  74. if (keep == false) {
  75. FOR(i, tin[u], tout[u])
  76. del(etour[i]);
  77. }
  78. }
  79.  
  80. void solve() {
  81. cin >> numNode;
  82. FOR(i, 1, numNode - 1) {
  83. int u, v;
  84. cin >> u >> v;
  85. G[u].pb(v);
  86. G[v].pb(u);
  87. }
  88. FOR(i, 1, numNode) cin >> a[i];
  89.  
  90. DFS(1, -1);
  91. dsu_ontree(1, -1, false);
  92.  
  93. cout << ans;
  94. }
  95.  
  96. int main() {
  97. ios_base::sync_with_stdio(0);
  98. cin.tie(0); cout.tie(0);
  99. if (fopen(task".inp", "r")){
  100. freopen(task".inp", "r", stdin);
  101. freopen(task".out", "w", stdout);
  102. }
  103. int tc = 1;
  104. // cin >> tc;
  105. while(tc--) solve();
  106. return 0;
  107. }
  108.  
Success #stdin #stdout 0.01s 12668KB
stdin
Standard input is empty
stdout
Standard output is empty