Test instructions: Given a tree of n nodes with Edge, first the longest road of each point is required, then the sequence d[1],d[2]...d[n], and then the maximum interval length of the interval minimum value <=k is satisfied.
Ideas:
In two steps:
(1) A maximum of 3 Dfs can be used to find the longest way for each point in O (n) time. Starting from any point T to traverse a bit, recorded from point T to each point of the longest road, and then from the record one of the points from the farthest point root, and then Dfs, you can get away from the root of the point E, and then from E Dfs once, get all the points of the longest road. Notice that 3 times the DFS code is the same!
(2) to satisfy the requirements of the maximum interval length can be achieved with two monotone queue, but also O (n) can be solved. The monotone queue to see this article.
1 //#include <bits/stdc++.h>2#include <vector>3#include <iostream>4#include <cstdio>5#include <cstring>6 #definePII pair<int,int>7 #defineINF 0x3f3f3f3f8 #defineLL Long Long9 using namespacestd;Ten Const intn=1e6+Ten; One A structnode - { - int from, To,len,next; the node () {}; -Nodeint from,intTo,intLenintNext): from( from), to, Len (Len), next (next) {}; -}edge[n*2]; - intedge_cnt, N, K, A, B, root; + intHead[n]; - voidAdd_node (int from,intTo,intlen) + { AEdge[edge_cnt]=node ( from, to,len,head[ from]); athead[ from]=edge_cnt++; - } - - intDis[n]; - voidDFS (intTintFarintlen) - { indis[t]=Max (dis[t], Len); - node E; to for(intI=HEAD[T]; i!=-1; I=e.next) + { -E=Edge[i]; the if(E.to!=far) DFS (e.to, T, len+E.len); * } $ if(Dis[t]>dis[root]) root=t;//to find the farthest pointPanax Notoginseng } - the voidGet_dis () + { ADFS (root=1,-1,0);//start at a random point. theDFS (root,-1,0);//start at the farthest point from point 1 . +DFS (root,-1,0);//start at the farthest point from the last root. - } $ $ intMax_que[n], min_que[n]; - intCal ()//maximum interval for monotone queue - { the intL=1, r=0, ans=0, st1=0, ed1=-1, st2=0, ed2=-1; - while(++r<=N)Wuyi { the intVal=Dis[r]; - while(st1<=ed1 && val>=dis[max_que[ed1]) ed1--; Wumax_que[++ed1]=R; - About while(St2<=ed2 && val<=dis[min_que[ed2]) ed2--; $min_que[++ed2]=R; - - while(dis[max_que[st1]]-dis[min_que[st2]]>k) - { Al++; + while(max_que[st1]<l) st1++; the while(min_que[st2]<l) st2++; - } $Ans=max (ans,r-l+1); the } the returnans; the } the - intMain () in { the //freopen ("Input.txt", "R", stdin); thescanf"%d%d",&n,&k); About theEdge_cnt=0; the for(intI=0; i<=n; i++) head[i]=-1; the + for(intI=1; i<n; i++) - { thescanf"%d%d",&a,&b);BayiAdd_node (i+1, A, b); theAdd_node (a,i+1, b); the } - Get_dis (); -printf"%d\n", Cal ());//Monotone Queue resolution the return 0; the}
AC Code
POJ 3162 Walking Race (tree diameter, monotone queue)