本文主要是介绍HDU 4123 Bob’s Race 树形DP + RMQ,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4123
代码:
//#include <bits/stdc++.h>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
const int maxn = 50000 + 5;
int max(int a,int b){return a > b ? a : b;}
int min(int a,int b){return a < b ? a : b;}
struct Edge{int v,c,pre;
}edges[maxn * 2];
int head[maxn],tot,n;
void Edge_Init(){memset(head,-1,sizeof head),tot = 0;
}
void Edge_Insert(int u,int v,int c){edges[tot].v = v;edges[tot].c = c;edges[tot].pre = head[u];head[u] = tot++;
}
int dis[maxn][4],path[maxn],logv[maxn],tmpv[maxn];
void DFS(int rt,int fa){int i,v,c;dis[rt][0] = dis[rt][1] = 0;for(i = head[rt];~i;i = edges[i].pre){v = edges[i].v,c = edges[i].c;if(v == fa) continue;DFS(v,rt);if(dis[rt][0] < dis[v][0] + c){dis[rt][0] = dis[v][0] + c,path[rt] = v;}}for(i = head[rt];~i;i = edges[i].pre){v = edges[i].v,c = edges[i].c;if(v == fa || v == path[rt]) continue;if(dis[rt][1] < dis[v][0] + c) dis[rt][1] = dis[v][0] + c;}
}
void DFS2(int rt,int fa){int i,v,c;dis[rt][3] = max(dis[rt][0],max(dis[rt][1],dis[rt][2]));for(i = head[rt];~i;i = edges[i].pre){v = edges[i].v,c = edges[i].c;if(v == fa) continue;if(v == path[rt]) dis[v][2] = max(dis[rt][1] + c,dis[rt][2] + c);else dis[v][2] = max(dis[rt][0],max(dis[rt][1],dis[rt][2])) + c;DFS2(v,rt);}
}
int min_st[maxn][32],max_st[maxn][32];
void ST_INIT(){for(int i = 1;i <= n;++i) min_st[i][0] = max_st[i][0] = dis[i][3];for(int i = 1;(1 << i) <= n;++i){for(int j = 1;j + (1 << i) <= n + 1;++j){min_st[j][i] = min(min_st[j][i - 1],min_st[j + tmpv[i - 1]][i - 1]);max_st[j][i] = max(max_st[j][i - 1],max_st[j + tmpv[i - 1]][i - 1]);}}
}int RMQ(int l,int r){int cnt = r - l + 1,k = 0;
// while((1 << k + 1) < cnt) k++;k = logv[cnt];return max(max_st[l][k],max_st[r - tmpv[k] + 1][k]) - min(min_st[l][k],min_st[r - tmpv[k] + 1][k]);
}
int main(){tmpv[0] = 1;for(int i = 1;i < maxn;++i) tmpv[i] = tmpv[i - 1] << 1,logv[i] = floor(log(i) / log(2));int op_c,tmp,ans,left;while(scanf("%d %d",&n,&op_c) != EOF && (n || op_c)){Edge_Init();for(int i = 1;i < n;++i){int u,v,c;scanf("%d %d %d",&u,&v,&c);Edge_Insert(u,v,c);Edge_Insert(v,u,c);}DFS(1,0);DFS2(1,0);ST_INIT();while(op_c--){scanf("%d",&tmp);ans = 0,left = 1;for(int i = 1;i <= n;++i){while(left <= i && RMQ(left,i) > tmp) left++;ans = max(ans,i - left + 1);}printf("%d\n",ans);}}
}
这篇关于HDU 4123 Bob’s Race 树形DP + RMQ的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!