Advertisement
Dmaxiya

团建 参考代码

Mar 26th, 2025
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. typedef long long LL;
  5. const int maxn = 200000 + 100;
  6. int n, m, u, v;
  7. int c[maxn], d[maxn];
  8. vector<int> G1[maxn], G2[maxn];
  9. map<int, int> mp[maxn];
  10.  
  11. void dfs1(int root, int fa) {
  12.     for (int pos : G1[root]) {
  13.         if (pos == fa) {
  14.             continue;
  15.         }
  16.         mp[root][c[pos]] = pos;
  17.         dfs1(pos, root);
  18.     }
  19. }
  20.  
  21. int dfs2(int root, int fa, int other) {
  22.     int mx = 0;
  23.     map<int, int>::iterator it;
  24.     for (int pos : G2[root]) {
  25.         if (pos == fa) {
  26.             continue;
  27.         }
  28.         it = mp[other].find(d[pos]);
  29.         if (it != mp[other].end()) {
  30.             mx = max(mx, dfs2(pos, root, it->second));
  31.         }
  32.     }
  33.     return mx + 1;
  34. }
  35.  
  36. int main() {
  37. #ifdef ExRoc
  38.     freopen("test.txt", "r", stdin);
  39. #endif
  40.     ios::sync_with_stdio(false);
  41.  
  42.     cin >> n >> m;
  43.     for (int i = 1; i <= n; ++i) {
  44.         cin >> c[i];
  45.     }
  46.     for (int i = 1; i <= m; ++i) {
  47.         cin >> d[i];
  48.     }
  49.     for (int i = 1; i < n; ++i) {
  50.         cin >> u >> v;
  51.         G1[u].push_back(v);
  52.         G1[v].push_back(u);
  53.     }
  54.     for (int i = 1; i < m; ++i) {
  55.         cin >> u >> v;
  56.         G2[u].push_back(v);
  57.         G2[v].push_back(u);
  58.     }
  59.     dfs1(1, 1);
  60.     if (c[1] != d[1]) {
  61.         cout << 0 << endl;
  62.         return 0;
  63.     }
  64.     cout << dfs2(1, 1, 1) << endl;
  65.  
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement