poj 3162 树DP+单调队列
http://acm.hust.edu.cn/vjudge/problem/11552
http://blog.csdn.net/woshi250hua/article/details/7727677
题目大意:给定一张地图,它是一棵n个节点的树。mm爱跑步,mm要跑n天,每次都从一个结点开始跑步,每次都要跑到最远的那个结点,两天跑的最远距离有个差值,现在要从这n天里去若干天使得这些天的差值都小于m,问怎么取使得天数最多?n <= 100万,m <= 1亿。
先求每个点到其他点距离最小值
再求小于m最长的区间范围
如果掌握
hdu 2196 叶子节点最长距离
http://www.cnblogs.com/qlky/p/5774759.html
以及hdu 3530 区间和在一定范围内最大区间
http://www.cnblogs.com/qlky/p/5791485.html
那么这题太简单了,10分钟内肯定能AC
求最大区间用线段树(5000+MS)也能做,但单调队列快很多,2600MS
#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("!\n") #define MAXN 1000000+5 #define MAX(a,b) a>b?a:b #define blank pf("\n") #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); 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 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]]>m) { 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)) { init(); for(i=2;i<=n;i++) { int x,y,z; sf("%d%d",&x,&y); add(i,x,y); add(x,i,y); } dfs(1,0); dfs2(1,0); /* for(i=1;i<=n;i++) pf("%d ",mx[i]); blank; */ getL(); pf("%d\n",ans); } }