【无标题】

路径相关树形DP

01树上路径

#include <bits/stdc++.h>
using namespace std;
using LL = long long;
const int N = 2005;
vector<int>e[N],t;
struct asdf{
    vector<int> vec;
    LL val;
};
vector<asdf>w[N];
LL dp[N];
int n,m,k,dep[N]={1},f[N];
void dfs(int u)
{
    for (auto v:e[u])
    {
        dfs(v);
        dp[u]+=dp[v];
    }
    for (auto t:w[u])
    {
        LL sum=dp[u];
        for (auto nw:t.vec)
        {
            sum-=dp[nw];
            for (auto v:e[nw]) sum+=dp[v];
        }
        dp[u]=max(dp[u],sum+t.val);
    }
}
int main()
{
    cin.tie(0);
    cout.tie(0);
    ios::sync_with_stdio(0);
    cin>>n>>m;
    for (int i=2;i<=n;++i)
    {
        cin>>f[i];
        e[f[i]].push_back(i);
        dep[i]=dep[f[i]]+1;
    }
    for (int i=1,x,y;i<=m;++i)
    {
        LL val;
        cin>>x>>y>>val;
        t.clear();
        while (x!=y)
            if (dep[x]>dep[y]) t.push_back(x),x=f[x];
            else t.push_back(y),y=f[y];
        t.push_back(x);
        w[x].push_back({t,val});
    }
    dfs(1);
    cout<<dp[1];
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
using LL=long long;
int n,m;
const int N=2005;
struct asdf{
    int x;
    LL val;
};
vector<asdf> w[N];
vector<int>e[N];
int dep[N];
LL dp[N][N];
void dfs(int u)
{
    LL sum=0;
    for (int i=1;i<=dep[u];++i) dp[u][i]=1e18;
    for (auto v:e[u])
    {
        dfs(v);
        sum+=dp[v][dep[u]+1];
        if (sum>=1e18)
        {
            cout<<-1;
            exit(0);
        }
        for (int i=1;i<=dep[u];++i)
            dp[u][i]=min(dp[u][i],dp[v][i]-dp[v][dep[u]+1]);
    }
    for (int i=1;i<=dep[u];++i) dp[u][i]+=sum;
    for (auto v:w[u])
        dp[u][dep[v.x]]=min(dp[u][dep[v.x]],sum+v.val);
    for (int i=2;i<=dep[u];++i) dp[u][i]=min(dp[u][i],dp[u][i-1]);
}
int main()
{
    cin>>n>>m;
    dep[1]=1;
    for (int i=2;i<=n;++i)
    {
        int f;
        cin>>f;
        e[f].push_back(i);
        dep[i]=dep[f]+1;
    }
    for (int i=1;i<=m;++i)
    {
        int x,y;
        LL val;
        cin>>x>>y>>val;
        if (dep[x]>dep[y]) swap(x,y);
        w[y].push_back({x,val});
    }
    dfs(1);
    cout<<dp[1][1];
    return 0;
}
  • 24
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值