A and B are going to travel. There are N cities. The roads in these cities are a tree. And the edges are directed. A and B are traveling from 0. A is too lazy to walk as little as possible. B is very energetic and wants to walk as much as possible, but no matter how you choose their total journey, it must be within the range of [L, R. So they choose the path that they choose. Start from B. Then you will be asked if you adopt the optimal strategy. The maximum number of steps B can perform.
Idea: Use dp [I] to indicate that the node I can obtain the maximum value. A tree-like DP is not difficult. Note that the length of the node from the beginning to the present is recorded, in addition, it is relatively simple to select B first and then select B in turn.
#include
#include
#include
#include #include
using namespace std;const int INF = 0x3f3f3f3f;const int MAXN = 500050;struct edge{ int v,w; edge(){} edge(int vv,int ww):v(vv),w(ww){}};vector
arr[MAXN];int L,R,n;int dp[MAXN];void dfs(int x,int cnt,int pres){ dp[x] = 0; if (arr[x].size() == 0) return; int temp = 0; if (cnt & 1){ temp = INF; for (int i = 0; i < arr[x].size(); i++){ int y = arr[x][i].v; dfs(y,cnt+1,pres+arr[x][i].w); if (pres + dp[y] + arr[x][i].w >= L && pres + dp[y] + arr[x][i].w <= R) temp = min(temp,dp[y]+arr[x][i].w); } dp[x] = temp; } else { temp = -INF; for (int i = 0; i < arr[x].size(); i++){ int y = arr[x][i].v; dfs(y,cnt+1,pres+arr[x][i].w); if (pres + dp[y] + arr[x][i].w >= L && pres + dp[y] + arr[x][i].w <= R) temp = max(temp,dp[y]+arr[x][i].w); } dp[x] = temp; }}int main(){ while (scanf("%d%d%d",&n,&L,&R) != EOF){ int x,y,z; for (int i = 0; i < n; i++) arr[i].clear(); for (int i = 0; i < n-1; i++){ scanf("%d%d%d",&x,&y,&z); arr[x].push_back(edge(y,z)); } dfs(0,0,0); if (dp[0] >= L && dp[0] <= R) printf("%d\n",dp[0]); else printf("Oh, my god!\n"); } return 0;}