标签:des style blog http java color
5 5 1 2 3 2 3 4 4 5 3 3 4 2 1 2 3 4 5 0 0
1 3 3 3 5
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <string> #include <map> #include <stack> #include <vector> #include <set> #include <queue> #pragma comment (linker,"/STACK:102400000,102400000") #define maxn 50005 #define MAXN 100005 #define mod 1000000009 #define INF 0x3f3f3f3f #define pi acos(-1.0) #define eps 1e-6 typedef long long ll; using namespace std; int n,m,ans,cnt,tot,flag; int len,st,ed; // 直径 起点 终点 bool vis[maxn]; int head[maxn],val[maxn],dist[maxn][2]; int f[maxn][20],g[maxn][20],lg[maxn]; //第二维为二进制 struct Node { int v,w,next; } edge[MAXN]; void addedge(int u,int v,int w) { cnt++; edge[cnt].v=v; edge[cnt].w=w; edge[cnt].next=head[u]; head[u]=cnt; } void dfs(int u,int fa,int sum) { if(sum>len){ len=sum;st=u; } int i,j,v; for(i=head[u];i;i=edge[i].next) { v=edge[i].v; if(v!=fa) { dfs(v,u,sum+edge[i].w); } } } void dfs1(int u,int fa,int k,int sum) { dist[u][k]=sum; int i,j,v; for(i=head[u];i;i=edge[i].next) { v=edge[i].v; if(v!=fa) dfs1(v,u,k,sum+edge[i].w); } } void init_rmq() // 预处理 O(n*log(n)) { int i,j; for(i=1;i<=n;i++) { f[i][0]=g[i][0]=val[i]; } for(j=1;(1<<j)<=n;j++) { for(i=1;i+j-1<=n;i++) { if((i+(1<<(j-1))<=n)) { f[i][j]=max(f[i][j-1],f[i+(1<<(j-1))][j-1]); //避免越界 g[i][j]=min(g[i][j-1],g[i+(1<<(j-1))][j-1]); } else { f[i][j]=f[i][j-1]; g[i][j]=g[i][j-1]; } } } } int query_rmq(int l,int r) { int k=lg[r-l+1]; return max(f[l][k],f[r-(1<<k)+1][k])-min(g[l][k],g[r-(1<<k)+1][k]); } int main() { int i,j,t; lg[1]=0; for(i=2;i<=50000;i++) { lg[i]=lg[i>>1]+1; } while(~scanf("%d%d",&n,&m)) { if(n==0&&m==0) break ; cnt=0; memset(head,0,sizeof(head)); int u,v,w; for(i=1;i<n;i++) { scanf("%d%d%d",&u,&v,&w); addedge(u,v,w); addedge(v,u,w); } len=0; dfs(1,0,0); ed=st; len=0; dfs(st,0,0); dfs1(st,0,0,0); dfs1(ed,0,1,0); for(i=1;i<=n;i++) { val[i]=max(dist[i][0],dist[i][1]); // printf("i:%d val:%d\n",i,val[i]); } init_rmq(); int q,le,ri,mid,res,id; while(m--) { scanf("%d",&q); ans=id=1; for(i=1;i<=n;i++) { while(id<=i) { res=query_rmq(id,i); if(res>q) id++; else break ; } ans=max(ans,i-id+1); } printf("%d\n",ans); } } return 0; }
hdu 4123 Bob’s Race (树的直径相关+rmq+单调队列思想),布布扣,bubuko.com
hdu 4123 Bob’s Race (树的直径相关+rmq+单调队列思想)
标签:des style blog http java color
原文地址:http://blog.csdn.net/tobewhatyouwanttobe/article/details/35602769