$ Luogu2680 / NOIp2015 $ transportation plan

Portal

$Sol$

The most violent approach is to enumerate the longest side of the chain, and then counted once all chain lengths, updated $ ans $.

Here requires the largest minimum, easy to think half the answer. For half the value of $ mid $, sweeping through all the chain, if the chain length is less than equal to $ mid $, it is legal does not require treatment. Otherwise, recording all the chain the number of edges through $ 1 + $ finally find the number of passes being equal to the number of chains chain length MID $ $ maximum side, into 0, look at the longest chain is smaller than or equal MID $. $ If no such side, then $ mid $ is clearly illegal, is too small.

Maintenance times through the side of a tree difference.

$Code$

 

#include<bits/stdc++.h>
#define il inline
#define Ri register int
#define go(i,a,b) for(Ri i=a;i<=b;++i)
#define yes(i,a,b) for(Ri i=a;i>=b;--i)
#define e(i,u) for(Ri i=b[u];i;i=a[i].nt)
#define mem(a,b) memset(a,b,sizeof(a))
#define ll long long
#define db double
#define inf 2147483647
using namespace std;
il int read()
{
    Ri x=0,y=1;char c=getchar();
    while(c<'0'||c>'9'){if(c=='-')y=-1;c=getchar();}
    while(c>='0'&&c<='9'){x=(x<<1)+(x<<3)+c-'0';c=getchar();}
    return x*y;
}
const int N=300010;
int n,m,b[N],ct,dep[N],f[N][19],dis[N],t[N],num,dd,as;
bool fl;
struct nd{int v,w,nt;}a[N*2];
struct nd1{int u,v,l,lc;}c[N];
il void add(Ri u,Ri v,Ri w){a[++ct]=(nd){v,w,b[u]};b[u]=ct;}
il void build(Ri u,Ri fa)
{
    dep[u]=dep[fa]+1;
    f[u][0]=fa;
    go(i,1,18)f[u][i]=f[f[u][i-1]][i-1];
    e(i,u)
    {
    if(a[i].v==fa)continue;
    dis[a[i].v]=dis[u]+a[i].w;
    build(a[i].v,u);
    }
}
il int lca(Ri u,Ri v)
{
    if(dep[u]<dep[v])swap(u,v);
    yes(i,18,0)if(dep[f[u][i]]>dep[v])u=f[u][i];
    if(dep[u]!=dep[v])u=f[u][0];
    if(u==v)return u;
    yes(i,18,0)if(f[u][i]!=f[v][i])u=f[u][i],v=f[v][i];
    return f[u][0];
}
il bool cmp(nd1 x,nd1 y){return x.l>y.l;}
il int dfs(Ri u)
{
    Ri ret=0;
    e(i,u)
    {
    if(a[i].v==f[u][0])continue;
    Ri qvq=dfs(a[i].v);ret+=qvq;
    if(qvq==num)fl=1,dd=max(dd,a[i].w);
    }
    ret+=t[u];
    return ret;
}
il bool ck(Ri x)
{
    if(c[1].l<=x)return 1;
    mem(t,0);num=0;dd=0;fl=0;
    go(i,1,m)
    {
    if(c[i].l<=x)break;
    Ri u=c[i].u,v=c[i].v,lc=c[i].lc;
    ++t[u];++t[v];t[lc]-=2;++num;
    }
    dfs(1);
    if(!fl)return 0;
    if(c[1].l-dd>x)return 0;
    return 1;
}
int main()
{
    n=read(),m=read();
    go(i,1,n-1){Ri u=read(),v=read(),w=read();add(u,v,w);add(v,u,w);}
    build(1,0);
    go(i,1,m)
    {
    Ri u=read(),v=read(),lc=lca(u,v);
    c[i]=(nd1){u,v,dis[u]+dis[v]-2*dis[lc],lc};
    }
    sort(c+1,c+n+1,cmp);
    Ri l=0,r=c[1].l+1;
    while(l<=r)
    {
    Ri mid=(l+r)>>1;
    if(ck(mid))as=mid,r=mid-1;
    else l=mid+1;
    }
    printf("%d\n",as);
    return 0;
}
View Code

 

Guess you like

Origin www.cnblogs.com/forward777/p/11560098.html