NOIP2015 day2t3 运输计划

来源:互联网 发布:ug编程教程入门视频 编辑:程序博客网 时间:2024/06/05 05:53

统计路径经过次数的差分+二分答案+倍增lca


BZOJ 4326(10080ms)
codevs 4632(最后一个点过不了)
写了俩小时还是没法过codevs最后一个点感觉自己萌萌哒,主函数里第一个乱糟糟的for循环其实就是建边,只不过被me拆掉写了······

但是CSDN id:_傲寒 的代码过了,可以去看一看他的
http://blog.csdn.net/qq_30401759/article/details/49777821


贴代码:

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;int n,m,head[300001],tw=0;struct path{    int pre,to,len;}w[600001];int anc[20][300001],lca[300001],dep[300001],maxdist=-1,cnt,now,mid;int st[300001],ed[300001],pass[300001],dis[300001],dist[300005],ok;void build_tree(int u,int f){    anc[0][u]=f;    dep[u]=dep[f]+1;    for(int i=head[u];i;i=w[i].pre)        if(w[i].to!=f){            dis[w[i].to]=w[i].len+dis[u];            build_tree(w[i].to,u);        }}void getst(){    int i,j;    for(j=1;j<=19;j++)        for(i=1;i<=n;i++)            anc[j][i]=anc[j-1][anc[j-1][i]];}int getlca(int u,int v){    if( dep[u] < dep[v] ) swap(u,v);    int t = dep[u] - dep[v];    for( int p = 0; t; t>>=1,p++ )        if( t & 1 ) u = anc[p][u];    if( u == v ) return u;    for( int p = 19; p >= 0; p-- )         if( anc[p][u] != anc[p][v] )            u = anc[p][u], v = anc[p][v];    return anc[0][u];}void updata(int u,int f){    if(ok==1)   return;    int i;    for(i=head[u];i;i=w[i].pre)        if(w[i].to!=f){            updata(w[i].to,u);            pass[u]+=pass[w[i].to];        }    if(pass[u]==cnt&&maxdist-dis[u]+dis[anc[0][u]]<mid){        ok=1;now=u;    }}int solve(int L,int R){    if(L>R) return R;    memset(pass,0,sizeof(pass));    mid=(L+R)/2;cnt=0;    for(register int i=1;i<=m;i++){        if(dist[i]>=mid){            cnt++;            pass[st[i]]+=1;            pass[ed[i]]+=1;            pass[lca[i]]+=-2;        }    }    ok=0;    updata(1,0);    if(ok==1) return solve(L,mid-1);    return solve(mid+1,R);}char ch;int data;inline int read(){    data=0;ch=0;    while(ch<'0' || ch>'9') ch=getchar();    while(ch>='0' && ch<='9') data=data*10+ch-'0',ch=getchar();    return data;}int main(){    int t1;    scanf("%d%d",&n,&m);    for(register int i=1;i<n;i++){        t1=read();        w[++tw].pre=head[t1];        w[tw].to=read();        w[tw].len=read();        head[t1]=tw;        w[++tw].pre=head[w[tw-1].to];        w[tw].to=t1;        w[tw].len=w[tw-1].len;        head[w[tw-1].to]=tw;    }    build_tree(1,0);    getst();    for(register int i=1;i<=m;i++){        st[i]=read();ed[i]=read();        lca[i]=getlca(st[i],ed[i]);        dist[i]=dis[st[i]]+dis[ed[i]]-2*dis[lca[i]];        maxdist=max(maxdist,dist[i]);    }    printf("%d",solve(1,maxdist));} 
原创粉丝点击