NC219631. Prospecting
描述
输入描述
The first line of input contains an integer , the number of nodes in the tree representing Pete's mine. The remaining input consists of lines, the th of which (starting at ) contains three integers , , and encoding information about the th node of the tree. is the index of the th node's parent in the tree. A parent index of zero means that the node's parent is the mine entrance (root of the tree). is the value of the ore in node , and is the length of the tunnel connecting node to node . Exactly one node has , indicating that the node contains the motherlode; all other inputs satisfy .Note that node zero is the mine entrance; it contains no ore and has no corresponding line in the input. You may assume that the motherlode is a leaf of the tree (no node has the motherlode node as a parent).
输出描述
Print two space-separated integers and , the worst-case and best-case investment Pete needs in order to clear a path to the motherlode, as described in more detail above.
示例1
输入:
5 0 3 1 0 0 2 2 -1 1 2 0 5
输出:
8 1
示例2
输入:
5 0 -1 4 0 2 1 0 4 3 0 3 2
输出:
7 1
C++(clang++11) 解法, 执行用时: 140ms, 内存消耗: 15556K, 提交时间: 2021-03-23 13:52:51
#include<bits/stdc++.h> #define ll long long #define pb push_back #define fors(i, a, b) for(int i = (a); i < (b); ++i) using namespace std; typedef pair<int,int> pii; const int maxn = 2e5 + 50; int x[maxn], y[maxn],n; vector<int> g[maxn]; const int inf = 0x3f3f3f3f; void init() { scanf("%d", &n); fors(i,1,n) { int p; scanf("%d%d%d", &p, &x[i], &y[i]); if(x[i] == -1) x[i] = inf; g[p].pb(i); } } int dfs_worst(int u) { int res = y[u] - x[u]; for(int v: g[u]) res += dfs_worst(v); return max(res, y[u]-1); } int it[maxn], p[maxn]; int dfs(int u) { int invest=inf; p[u]=x[u]-y[u]; for(auto v:g[u]) { p[u]+=max(0,dfs(v)); if(p[v]>0) invest=min(invest,it[v]); } it[u]=y[u]<x[u]?y[u]:max(y[u],y[u]-x[u]+invest); return p[u]; } int dfs_best() { int cur,money(0),cost(0); priority_queue<pii,vector<pii>,greater<> >que; dfs(0); que.emplace(0,0); do{ cur=que.top().second; que.pop(); cost=max(cost,y[cur]-money); money+=x[cur]-y[cur]; for(auto v:g[cur]) if(p[v]>0) que.emplace(it[v],v); }while(x[cur]!=inf); return cost; } int main() { init(); printf("%d %d\n",dfs_worst(0)+1,dfs_best()); } /* 5 0 100 9 0 0 6 2 -1 6 2 4 2 */