比赛 CSP2023-J模拟赛 评测结果 AAAAAAAAAA
题目名称 新建题目 最终得分 100
用户昵称 usr10086 运行时间 0.293 s
代码语言 C++ 内存使用 3.59 MiB
提交时间 2023-10-18 20:04:13
显示代码纯文本
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. const int N = 2e3 + 10;
  6.  
  7. ifstream fin("touch.in");
  8. ofstream fout("touch.out");
  9. #define cin fin
  10. #define cout fout
  11.  
  12. struct D
  13. {
  14. int i, down;
  15. };
  16.  
  17. bool vis[N];
  18. int n, fa[N], w[N], dep[N], path[N];
  19. vector<int> son[N], g[N];
  20.  
  21. void dfs(int x, int fa)
  22. {
  23. dep[x] = dep[fa]+1; ::fa[x] = fa;
  24. for (int y : g[x])
  25. {
  26. if (y == fa) continue;
  27. son[x].push_back(y);
  28. dfs(y, x);
  29. }
  30. }
  31.  
  32. int main()
  33. {
  34. cin >> n;
  35. for (int i = 1; i <= n; i++) cin >> w[i];
  36. for (int i = 1, u, v; i <= n-1; i++)
  37. cin >> u >> v, g[u].push_back(v), g[v].push_back(u);
  38. dfs(1, 0);
  39. long long ans = 0;
  40. for (int i = 1; i <= n; i++)
  41. {
  42. int x = i;
  43. while (x) path[dep[x]] = x, x = fa[x];
  44. x = i;
  45. memset(vis, 0, sizeof(bool)*(n+1));
  46. queue<D> q;
  47. q.push({i, false}); vis[i] = true;
  48. int cnt = 0;
  49. while (!q.empty())
  50. {
  51. D k = q.front(); q.pop();
  52. cnt++;
  53. int i = k.i, down = k.down;
  54. if (!down)
  55. {
  56. int f = fa[i];
  57. if (f && !vis[f] && w[f] < w[i]) vis[f] = true, q.push({f, false});
  58. }
  59. for (int y : son[i])
  60. if (!vis[y] && (w[y] > max(w[i], w[path[dep[i]]]) && (dep[y] >= dep[x] || w[y] < w[path[dep[y]+1]]))) vis[y] = true, q.push({y, true});
  61. }
  62. for (int d = 0; d <= dep[x]; d++) path[d] = 0;
  63. ans += (cnt-1); // i->i does not count
  64. }
  65. cout << ans / 2;
  66. }
  67.