题意:给定一棵树,每个点有一个点权,每条边也是,找一条路径,问你 T-S-sum,T表示路径的终点的权值,S表示路径始点的权值,sum表示从S到T的边权和。
析:把这一条路径拆开来看,那么就是必然是从 a 先经过一个公共祖先 i,然后再到达b,所以,dp[i][0] 表示 从 i 结点到子树结点中能得到的最大值(到终点),dp[i][1] 表示从子结点到 i 结点能得到的最大值(始点),然后答案就是 dp[i][0] + dp[i][1]。
代码如下:
#pragma comment(linker, "/STACK:1024000000,1024000000") #include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <algorithm> #include <vector> #include <map> #include <cctype> #include <cmath> #include <stack> #include <sstream> #include <list> #include <assert.h> #include <bitset> #define debug() puts("++++"); #define gcd(a, b) __gcd(a, b) #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define fi first #define se second #define pb push_back #define sqr(x) ((x)*(x)) #define ms(a,b) memset(a, b, sizeof a) #define sz size() #define pu push_up #define pd push_down #define cl clear() #define all 1,n,1 #define FOR(x,n) for(int i = (x); i < (n); ++i) #define freopenr freopen("in.txt", "r", stdin) #define freopenw freopen("out.txt", "w", stdout) using namespace std; typedef long long LL; typedef unsigned long long ULL; typedef pair<int, int> P; const int INF = 0x3f3f3f3f; const double inf = 1e20; const double PI = acos(-1.0); const double eps = 1e-8; const int maxn = 1e5 + 50; const int mod = 1000; const int dr[] = {-1, 0, 1, 0}; const int dc[] = {0, 1, 0, -1}; const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}; int n, m; const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; inline bool is_in(int r, int c) { return r > 0 && r <= n && c > 0 && c <= m; } struct Edge{ int to, next, c; }; Edge edge[maxn<<1]; int head[maxn], cnt; int a[maxn]; void addEdge(int u, int v,int c){ edge[cnt].to = v; edge[cnt].c = c; edge[cnt].next = head[u]; head[u] = cnt++; } int dp[maxn][2]; int ans; void dfs(int u, int fa){ dp[u][0] = a[u]; dp[u][1] = -a[u]; for(int i = head[u]; ~i; i = edge[i].next){ int v = edge[i].to; if(v == fa) continue; dfs(v, u); dp[u][0] = max(dp[u][0], dp[v][0] - edge[i].c); dp[u][1] = max(dp[u][1], dp[v][1] - edge[i].c); } ans = max(ans, dp[u][0] + dp[u][1]); } int main(){ int T; cin >> T; while(T--){ scanf("%d", &n); for(int i = 1; i <= n; ++i) scanf("%d", a+i); ms(head, -1); cnt = 0; for(int i = 1; i < n; ++i){ int u, v, c; scanf("%d %d %d", &u, &v, &c); addEdge(u, v, c); addEdge(v, u, c); } ans = 0; dfs(1, -1); printf("%d ", ans); } return 0; }