CF 1083 A. The Fair Nut and the Best Path

A. The Fair Nut and the Best Path

https://codeforces.com/contest/1083/problem/A

题意:

  在一棵树内找一条路径,使得从起点到终点的最后剩下的油最多。(中途没油了不能再走了,可以在每个点加wi升油,减少的油量为路径长度)。

分析:

  dfs一遍可以求出子树内所有点到子树根节点的最大的路径和次大的路径,然后可以直接合并取max,并且和从根节点出发的路径取max。

  两条最大的和次大的合并可能不合法的。从最大的走上来后,不一定可以从根节点在走回去。但是即使不合法的取max是没有影响的,这样的路径一定不是更优的。

代码:

 #include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<cmath>
#include<cctype>
#include<set>
#include<queue>
#include<vector>
#include<map>
using namespace std;
typedef long long LL; inline int read() {
int x=,f=;char ch=getchar();for(;!isdigit(ch);ch=getchar())if(ch=='-')f=-;
for(;isdigit(ch);ch=getchar())x=x*+ch-'';return x*f;
} const int N = ; struct Edge{
int to, nxt, w;
Edge() {}
Edge(int a,int b,int c) { to = a, nxt = b, w = c; }
}e[N << ];
int head[N], w[N], En; inline void add_edge(int u,int v,int w) {
++En; e[En] = Edge(v, head[u], w); head[u] = En;
++En; e[En] = Edge(u, head[v], w); head[v] = En;
} LL f[N], Ans;
void dfs(int u,int fa) {
f[u] = w[u];
LL mx1 = -1e18, mx2 = -1e18;
for (int i = head[u]; i; i = e[i].nxt) {
int v = e[i].to;
if (v == fa) continue;
dfs(v, u);
LL t = f[v] - e[i].w;
if (t > mx1) mx2 = mx1, mx1 = t;
else if (t > mx2) mx2 = t;
if (f[v] > e[i].w) f[u] = max(f[u], f[v] - e[i].w + w[u]);
}
Ans = max(Ans, f[u]);
Ans = max(Ans, mx1 + mx2 + w[u]);
} int main() {
int n = read();
for (int i = ; i <= n; ++i) w[i] = read();
for (int i = ; i < n; ++i) {
int u = read(), v = read(), w = read();
add_edge(u, v, w);
}
dfs(, );
cout << Ans;
return ;
}
上一篇:【HDU 2196】 Computer(树的直径)


下一篇:XML序列化与反序列化