武汉大学2023年新生程序设计竞赛B题

题意

建立一棵树,每次查询在该节点以及最长深度为t的子树之间的点权最大值,也就是在要查询的节点的分支上,求向下深度0~t的点权的最大值。

代码实现

想着新生赛应该没那么难,于是用简单递归,没想到过了。^_^。我们只需要先存下来节点,然后给出查询,我们递归时间和节点,每次递归取最大值,最后返回的就是答案。

代码

#include <bits/stdc++.h>
#define IOS                    \
  ios::sync_with_stdio(false); \
  cin.tie(0), cout.tie(0);
#define debug(a) cout << "=======" << a << "========" << endl;
#define endl '\n'
#define c(a, b) cout << a << ' ' << b << endl
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int N = 5e5 + 10, mod = 1e9 + 7, T = 9901;
const double ex = 1e-7;
typedef pair<int, int> PII;
int dix[N];
int h[N], ne[N], e[N], w[N], idx;
int f[N];
int n, m, k;
void add(int x, int y)
{
  e[idx] = y;
  ne[idx] = h[x];
  h[x] = idx++;
}
int find(int t, int x)
{
  int ans = f[x];
  if (!t)//t为0的话直接返回
    return ans;
  for (int i = h[x]; i != -1; i = ne[i])
  {
    int j = e[i];
    ans = max(ans, find(t - 1, j));//依次递归取最大值
  }
  return ans;
}
int main()
{
  IOS
      memset(h, -1, sizeof h);
  cin >> n;
  for (int i = 1; i <= n; i++)
    cin >> f[i];
  for (int i = 1; i < n; i++)
  {
    int x, y;
    cin >> x >> y;
    add(x, y);
  }
  cin >> m;
  while (m--)
  {
    int t, x;
    cin >> t >> x;
    cout << find(t, x) << endl;
  }
  return 0;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Radon.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值