BZOJ1832: [AHOI2008]聚会

题目:http://www.lydsy.com/JudgeOnline/problem.php?id=1832

直接找三个点lca就可以了。这叫lca模版题。

#include<cstring>
#include<iostream>
#include<cstdio>
#include<map>
#include<cmath>
#include<algorithm>
#define rep(i,l,r) for (int i=l;i<=r;i++)
#define down(i,l,r) for (int i=l;i>=r;i--)
#define clr(x,y) memset(x,y,sizeof(x))
#define maxn 500500
#define inf 2000000000
#define mm 1000000007
using namespace std;
struct data{int obj,pre;
}e[maxn*2];
int head[maxn],bin[22],a[maxn],d[maxn],fa[maxn][22],tot,n,m;
int read(){
    int x=0,f=1; char ch=getchar();
    while (!isdigit(ch)) {if (ch=='-') f=-1; ch=getchar();}
    while (isdigit(ch)) {x=x*10+ch-'0'; ch=getchar();}
    return x*f;
}
void insert(int x,int y){
    e[++tot].obj=y; e[tot].pre=head[x]; head[x]=tot; 
}
void dfs(int u){
    rep(i,1,20) if (d[u]>=bin[i]) fa[u][i]=fa[fa[u][i-1]][i-1];
    for (int j=head[u];j;j=e[j].pre){
        int v=e[j].obj;
        if (v!=fa[u][0]) {
            fa[v][0]=u; d[v]=d[u]+1; 
            dfs(v);
        }
    }
}
int lca(int x,int y){
    if (d[x]<d[y]) swap(x,y);
    int t=d[x]-d[y];
    rep(i,0,20) if (t&bin[i]) x=fa[x][i];
    down(i,20,0) if (fa[x][i]!=fa[y][i]) x=fa[x][i],y=fa[y][i];
    if (x==y) return x;
    return fa[x][0];
}
int main(){
    //freopen("in.txt","r",stdin);
    bin[0]=1; rep(i,1,20) bin[i]=bin[i-1]*2;
    n=read(); m=read();
    rep(i,1,n-1){
        int x=read(),y=read();
        insert(x,y); insert(y,x);
    }
    d[1]=0;
    dfs(1);
    rep(i,1,m) {
        int ans=inf,ans2;
        int x=read(),y=read(),z=read(),t1=lca(x,y),t2=lca(y,z),t3=lca(x,z);
        if (d[x]+d[y]+d[z]-d[t1]-2*d[lca(z,t1)]<ans) ans=d[x]+d[y]+d[z]-d[t1]-2*d[lca(z,t1)],ans2=t1;
        if (d[x]+d[y]+d[z]-d[t2]-2*d[lca(x,t2)]<ans) ans=d[x]+d[y]+d[z]-d[t2]-2*d[lca(x,t2)],ans2=t2;
        if (d[x]+d[y]+d[z]-d[t3]-2*d[lca(y,t3)]<ans) ans=d[x]+d[y]+d[z]-d[t3]-2*d[lca(y,t3)],ans2=t3;
        printf("%d %d\n",ans2,ans);
    }
    return 0;
} 

 

posted on 2016-01-11 21:53  ctlchild  阅读(94)  评论(0编辑  收藏

导航