洛谷 P1131 时态同步
洛谷 P1131 时态同步
题目描述
给出一棵由
我们定义 “时态同步” 为 “以起点为根结点,所有叶子结点同时得到能量” 的状态。现在我们可以给任意一条边进行 “权值加一” 的操作。请你求出最少需要多少次操作,能达到 “时态同步” 的状态。
输入格式
第一行一个正整数
第二行一个正整数
接下来
输出格式
一行一个正整数,表示题目答案。
数据范围
对于所有测试数据,
思路
考虑
很好想到一种状态表示形式:
考虑转移。显然
现在问题就是如何处理上式的后半部分了。我们可以设置一个数组
那么对于
所以状态转移方程就变为:
遍历一边树,从下往上
代码
#include <iostream>
#include <algorithm>
#include <cstring>
#include <stdio.h>
using namespace std;
template <typename T>
inline void read(T &x)
{
T f =0;
x = 1;
char c = getchar();
while(c < '0' || c > '9')
{
if(c == '-') x = -1;
c = getchar();
}
while(c >= '0' && c <= '9')
{
f = (f << 3) + (f << 1) + (c ^ 48);
c = getchar();
}
x *= f;
}
typedef long long LL;
const int N = 5e5 + 10;
int n, root;
int h[N], ne[N], e[N], idx;
LL len[N], f[N], w[N]; //记得开long long
void add(int a, int b, LL c)
{
e[ ++ idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx;
}
void dp(int u, int last)
{
for(int i = h[u] ; i ; i = ne[i])
{
int j = e[i];
if(j == last) continue;
dp(j, u);
len[u] = max(len[u], len[j] + w[i]); //先转移len数组,转移结束后再转移f数组
}
for(int i = h[u] ; i ; i = ne[i])
{
int j = e[i];
if(j == last) continue;
f[u] += f[j] + len[u] - (len[j] + w[i]); //dp
}
}
int main()
{
read(n), read(root);
for(int i = 1 ; i < n ; i ++ )
{
int a, b;
LL c;
read(a), read(b), read(c);
add(a, b, c), add(b, a, c);
}
dp(root, 0);
printf("%lld\n", f[root]);
return 0;
}