[树的直径] BZOJ 1999 [Noip2007]Core树网的核

来源:互联网 发布:淘宝卖家电话在哪 编辑:程序博客网 时间:2024/06/05 18:59

做这个题 主要是复习几个性质

  • 对于树中的任意一点,距离其最远的点一定是树的直径的某一端点
  • 所有直径的中心相同,这个中心可以是一个顶点,也可以在一条边上。所有点到他的最远点都要通过这个中心
  • 所有的直径所能求出的该最小偏心距相等
  • 还有个很实用于合并信息的性质是树的直径的端点必然是他的子树直径的端点

然后我们就直接找出一条直径 在上面two-pointers扫一下就好了
每次我们用 当前区间内不经过直径上的点抵达的其他点的最大深度和到两端的距离的最大值 更新下答案

#include<cstdio>#include<cstdlib>#include<algorithm>using namespace std;inline char nc(){  static char buf[100000],*p1=buf,*p2=buf;  return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;}inline void read(int &x){  char c=nc(),b=1;  for (;!(c>='0' && c<='9');c=nc()) if (c=='-') b=-1;  for (x=0;c>='0' && c<='9';x=x*10+c-'0',c=nc()); x*=b;}const int N=500005;struct edge{  int u,v,w,next;}G[N<<1];int head[N],inum;inline void add(int u,int v,int w,int p){  G[p].u=u; G[p].v=v; G[p].w=w; G[p].next=head[u]; head[u]=p;}int depth[N],fat[N];int maxd,pt;int vst[N];#define V G[p].vinline void dfs(int u,int fa,int d){  fat[u]=fa; depth[u]=d;  if (d>maxd) maxd=d,pt=u;  for (int p=head[u];p;p=G[p].next)    if (V!=fa && !vst[V])      dfs(V,u,d+G[p].w);}int n,s;int a[N],m,val[N],dep[N];int Q[N],l,r;int main(){  int iu,iv,iw;  freopen("t.in","r",stdin);  freopen("t.out","w",stdout);  read(n); read(s);  for (int i=1;i<n;i++)    read(iu),read(iv),read(iw),add(iu,iv,iw,++inum),add(iv,iu,iw,++inum);  maxd=0; dfs(1,0,0);  maxd=0; dfs(pt,0,0);  int t=pt; while (t) a[++m]=t,dep[m]=depth[t],vst[t]=1,t=fat[t];  for (int i=1;i<=m;i++)    maxd=0,dfs(a[i],0,0),val[i]=maxd;  int L,R=0; l=r=-1;  int ans=1<<30;  for (L=1;L<=m;L++){    while (l<r && Q[l+1]<L) Q[++l]=0;    while (R+1<=m && dep[L]-dep[R+1]<=s){      R++;      while (l<r && val[R]>=val[Q[r]]) r--;      Q[++r]=R;    }    int ret=max(max(dep[1]-dep[L],dep[R]-dep[m]),val[Q[l+1]]);    ans=min(ans,ret);  }  printf("%d\n",ans);  return 0;}
0 0
原创粉丝点击