http://acm.hust.edu.cn/vjudge/problem/25790
这题基本同poj 3162
要注意mx,mx2,vx,vx2每次都要初始化
#include <iostream> #include <string> #include <cstring> #include <cstdlib> #include <cstdio> #include <cmath> #include <algorithm> #include <stack> #include <queue> #include <cctype> #include <vector> #include <iterator> #include <set> #include <map> #include <sstream> using namespace std; #define mem(a,b) memset(a,b,sizeof(a)) #define pf printf #define sf scanf #define spf sprintf #define pb push_back #define debug printf("! ") #define MAXN 50000+5 #define MAX(a,b) a>b?a:b #define blank pf(" ") #define LL long long #define ALL(x) x.begin(),x.end() #define INS(x) inserter(x,x.begin()) #define pqueue priority_queue #define INF 0x3f3f3f3f #define ls (rt<<1) #define rs (rt<<1|1) int n,m; int head[MAXN],vis[MAXN],ptr=1; int mx[MAXN],mx2[MAXN],vx[MAXN],vx2[MAXN]; int p1[MAXN],p2[MAXN],ans; struct node{int y,next,val;}tree[MAXN<<2]; void init() { mem(head,-1); mem(vis,0); mem(mx,0); mem(mx2,0); mem(vx,0); mem(vx2,0); ptr = 1; } void add(int son,int fa,int val) { tree[ptr].y=son; tree[ptr].val=val; tree[ptr].next=head[fa]; head[fa]=ptr++; } void dfs(int root,int fa) { for(int i = head[root];i!=-1;i=tree[i].next) { int y = tree[i].y; if(y==fa) continue; dfs(y,root); if(mx2[root]<mx[y]+tree[i].val) { vx2[root] = y; mx2[root] = mx[y]+tree[i].val; if(mx2[root]>mx[root]) { swap(vx2[root],vx[root]); swap(mx2[root],mx[root]); } } } } void dfs2(int root,int fa) { for(int i = head[root];i!=-1;i=tree[i].next) { int y = tree[i].y; if(y==fa) continue; if(y == vx[root]) { if(mx2[root]+tree[i].val > mx2[y]) { mx2[y] = mx2[root]+tree[i].val; vx2[y] = root; if(mx2[y]>mx[y]) { swap(vx2[y],vx[y]); swap(mx2[y],mx[y]); } } } else { if(mx[root]+tree[i].val > mx2[y]) { mx2[y] = mx[root]+tree[i].val; vx2[y] = root; if(mx2[y]>mx[y]) { swap(vx2[y],vx[y]); swap(mx2[y],mx[y]); } } } dfs2(y,root); } } void getL(int q) { int h1,h2,r1,r2,pre; h1=h2=pre=1; r1=r2=ans=0; for(int i=1;i<=n;i++) { while(h1<=r1 && mx[p1[r1]]>=mx[i]) r1--; p1[++r1] = i; while(h2<=r2 && mx[p2[r2]]<=mx[i]) r2--; p2[++r2] = i; while(h1<=r1 && h2<=r2 && mx[p2[h2]]-mx[p1[h1]]>q) { if(p1[h1]>p2[h2]) pre = p2[h2++]+1; else pre = p1[h1++]+1; } if(h1<=r1 && h2<=r2 && mx[p2[h2]]>=mx[p1[h1]]) { ans = max(ans,i-pre+1); } } } int main() { int i,j; while(~sf("%d%d",&n,&m),m+n) { init(); for(i=2;i<=n;i++) { int x,y,z; sf("%d%d%d",&x,&y,&z); add(y,x,z); add(x,y,z); } dfs(1,0); dfs2(1,0); /* for(i=1;i<=n;i++) pf("%d ",mx[i]); blank; */ int q; for(i=0;i<m;i++) { mem(p1,0); mem(p2,0); sf("%d",&q); getL(q); pf("%d ",ans); } } }