[图论] 树上不重复权值的路径数

解题思路

整体思路,枚举路径上每个点,记录这个点 u 可以向上延伸到多远,如果可延伸到 x 点,则这个点对答案的贡献为 dep[u] - dep[x](下文的maxx) + 1

为什么枚举是向上延伸?因为可以记录已走过路径中已有的权值,每到一个新的点,只需要知道这个点在已有路径上是否存在。用来实现的数据结构是 map 以权值为键,以出现的深度为值

如果遇到已有权值,应进行的操作是:更新这个路径上能向上延伸的最大深度 maxx ,如果有已出现的权值点 v ,需要 maxx = dep[v]+1,所以最后这个点对答案的贡献为 ans += dep[u] - maxx

注意:当遍历结束一个结点,并要回溯到父结点时,需要把当前结点从map中弹出。

代码

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
#define ll long long

const int N = 1e5+5;
vector<int> e[N];
int a[N];
map<int,vector<int>> m;
ll ans=0;

void dfs(int t,int dep,int maxx){
  if(m[a[t]].size()){
    maxx = max(m[a[t]].back(),maxx);
  }
  ans += dep-maxx;
  m[a[t]].push_back(dep);
  for(auto &y:e[t]){
    dfs(y,dep+1,maxx);
  }
  m[a[t]].pop_back();
  return ;
}


int main()
{
  int n;
  cin >> n;
  for(int i = 2 ; i <= n ; i++){
    int x;
    cin >> x;
    e[x].push_back(i);
  }
  for(int i = 1 ; i<=n ; i++){
    cin >> a[i];
  }
  dfs(1,1,0);
  cout << ans ;

  return 0;
}
相关推荐
燃于AC之乐4 小时前
我的算法修炼之路--8——预处理、滑窗优化、前缀和哈希同余,线性dp,图+并查集与逆向图
算法·哈希算法·图论·滑动窗口·哈希表·线性dp
2401_827499995 小时前
代码随想录-图论28
算法·深度优先·图论
ValhallaCoder5 小时前
Day51-图论
数据结构·python·算法·图论
ValhallaCoder20 小时前
Day53-图论
数据结构·python·算法·图论
(❁´◡`❁)Jimmy(❁´◡`❁)2 天前
Atcoder abc441A~F 题解
算法·深度优先·图论
ValhallaCoder2 天前
Day50-图论
数据结构·python·算法·图论
ValhallaCoder2 天前
Day49-图论
数据结构·python·算法·图论
wuqingshun3141592 天前
蓝桥杯 云神的子数组和
算法·蓝桥杯·图论
小魏每天都学习2 天前
【数据结构学习】
算法·图论
zc.ovo3 天前
线段树优化建图
数据结构·c++·算法·图论