Luogu 1131 Temporal synchronization (deceived fake tree dp)

Category: Search dfs

Portal: Temporal Synchronization

Title:

Tree structure [each node of the circuit board is connected by several disjoint wires, and for any two nodes of the circuit board, there is and only one path (path refers to the sequence of wires connecting two components)]
given in the question The cost of all edges is specified to make the cost from the root S to all termination nodes the same.
Ask, how much does it cost to add to all edges?
data range long long

Ideas:

dis[i] holds the maximum cost of the terminating node to i. //dfs starts from the leaf node and maintains it.
dp[u] saves the increased cost from the termination node to u
(false) Transfer equation:
dp[u] of the updated partial subtree + updated partial dp[v] of the current subtree + The cost to be increased between
uv The cost to be increased between uv, that is: the cost to increase from the termination node to u dis[u] - The cost to increase from the termination node to the current subtree v dis[v] - The edge from u to v weight w

#include<iostream>
#include<cstdio>
#include<string.h>
using namespace std;
typedef long long ll;
const int maxn=500005;

int n,s;
struct node
{
    int v,w,next;
}e[maxn<<1];
int head[maxn],num=0;
ll dis[maxn],dp[maxn];
void add(int u,int v,int w)
{
    e[num].v=v;
    e[num].w=w;
    e[num].next=head[u];
    head[u]=num++;
}
void dfs(int u,int fa)
{
    for(int i=head[u];~i;i=e[i].next)
    {
        int v=e[i].v;
        if(v==fa)continue;
        dfs(v,u);
        dis[u]=max(dis[u],dis[v]+e[i].w);
    }
}
void tree_dp(int u,int fa)
{
    for(int i=head[u];~i;i=e[i].next)
    {
        int v=e[i].v;
        if(v==fa)continue;
        tree_dp(v,u);
        dp[u]=dp[u]+dp[v]+dis[u]-dis[v]-e[i].w;
    }
}
int main()
{
    cin>>n>>s;
    memset(head,-1,sizeof(head));
    memset(dis,0,sizeof(dis));
    memset(dp,0,sizeof(dp));
    for(int i=1;i<n;i++)
    {
        int u,v,w;
        cin>>u>>v>>w;
        add(u,v,w);
        add(v,u,w);
    }
    dfs(s,-1);
    tree_dp(s,-1);
    cout<<dp[s]<<endl;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325686997&siteId=291194637