Advertisement
Dmaxiya

零食采购 参考代码

Mar 23rd, 2025
621
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. typedef long long LL;
  5. const int maxn = 100000 + 100;
  6. const int Log = 20;
  7. int n, q, u, v, s, t, cnt;
  8. int c[maxn], id[maxn];
  9. int st[maxn][Log], bitMask[maxn][Log];
  10. vector<int> G[maxn];
  11.  
  12. void dfs(int root, int fa) {
  13.     id[root] = ++cnt;
  14.     st[root][0] = fa;
  15.     bitMask[root][0] = 1 << c[root];
  16.     for (int i = 1; i < Log; ++i) {
  17.         st[root][i] = st[st[root][i - 1]][i - 1];
  18.         bitMask[root][i] = bitMask[root][i - 1] | bitMask[st[root][i - 1]][i - 1];
  19.     }
  20.     for (int pos : G[root]) {
  21.         if (pos == fa) {
  22.             continue;
  23.         }
  24.         dfs(pos, root);
  25.     }
  26. }
  27.  
  28. int solve(int s, int t) {
  29.     if (s == t) {
  30.         return 1;
  31.     }
  32.     if (id[s] > id[t]) {
  33.         swap(s, t);
  34.     }
  35.     int mask = 0;
  36.     for (int i = Log - 1; i >= 0; --i) {
  37.         if (id[st[t][i]] > id[s]) {
  38.             mask |= bitMask[t][i];
  39.             t = st[t][i];
  40.         }
  41.     }
  42.     mask |= bitMask[t][0];
  43.     t = st[t][0];
  44.     for (int i = Log - 1; i >= 0; --i) {
  45.         if (id[st[s][i]] > id[t]) {
  46.             mask |= bitMask[s][i];
  47.             s = st[s][i];
  48.         }
  49.     }
  50.     mask |= bitMask[s][0];
  51.     return __builtin_popcount(mask | (1 << c[t]));
  52. }
  53.  
  54. int main() {
  55. #ifdef ExRoc
  56.     freopen("test.txt", "r", stdin);
  57. #endif
  58.     ios::sync_with_stdio(false);
  59.  
  60.     cin >> n >> q;
  61.     for (int i = 1; i <= n; ++i) {
  62.         cin >> c[i];
  63.         --c[i];
  64.     }
  65.     for (int i = 1; i < n; ++i) {
  66.         cin >> u >> v;
  67.         G[u].push_back(v);
  68.         G[v].push_back(u);
  69.     }
  70.     dfs(1, 1);
  71.     while (q--) {
  72.         cin >> s >> t;
  73.         cout << solve(s, t) << endl;
  74.     }
  75.  
  76.     return 0;
  77. }
  78.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement