BZOJ1787: [Ahoi2008]Meet 紧急集合&1832: [AHOI2008]聚会

来源:互联网 发布:python 最优化算法包 编辑:程序博客网 时间:2024/06/05 01:58

以后根的dep要定1…不然LCA会炸…

因为好像没有这个类型只好随便分了一个类

树上的三个点找到一个点使得他们到这个点的距离和最小

A,B,C三点,对于A,B两点找一个点到他们的距离和最小,这个点一定在他们的路径上,对于A,B,C三点找一个点,这个点也一定在A,B的路径上,因为让一个人多走若干步一定比让两个人多走若干步优

求出两两的LCA,讨论一下就好了

code:

#include<set>#include<map>#include<deque>#include<queue>#include<stack>#include<cmath>#include<ctime>#include<bitset>#include<string>#include<vector>#include<cstdio>#include<cstdlib>#include<cstring>#include<climits>#include<complex>#include<iostream>#include<algorithm>#define ll long longusing namespace std;inline void swap(int &x,int &y){x^=y;y^=x;x^=y;}inline void read(int &x){    char c;    while(!((c=getchar())>='0'&&c<='9'));    x=c-'0';    while((c=getchar())>='0'&&c<='9') (x*=10)+=c-'0';}const int maxn = 510000;const int maxm = 510000;const int maxb = 21;struct edge{    int y,nex;    edge(){}    edge(const int &_y,const int &_nex){y=_y;nex=_nex;}}a[maxn<<1]; int len,fir[maxn];int n,m;inline void ins(const int &x,const int &y){a[++len]=edge(y,fir[x]);fir[x]=len;}int fa[maxn][maxb],dep[maxn];void dfs(const int &x){    for(int i=1;fa[x][i-1]&&i<maxb;i++)        fa[x][i]=fa[fa[x][i-1]][i-1];    for(int k=fir[x];k;k=a[k].nex)    {        const int y=a[k].y;        if(y!=fa[x][0])        {            fa[y][0]=x; dep[y]=dep[x]+1;            dfs(y);        }    }}int LCA(int x,int y){    if(dep[x]<dep[y]) swap(x,y);    for(int i=maxb-1;i>=0&&dep[x]!=dep[y];i--)        if(dep[fa[x][i]]>=dep[y]) x=fa[x][i];    if(x==y) return x;    for(int i=maxb-1;i>=0;i--)        if(fa[x][i]!=fa[y][i]) x=fa[x][i],y=fa[y][i];    return fa[x][0];}int main(){    read(n); read(m);    for(int i=1;i<n;i++)    {        int x,y; read(x); read(y);        ins(x,y); ins(y,x);    }    dep[1]=1; dfs(1);    for(int i=1;i<=m;i++)    {        int t1,t2,t3; read(t1); read(t2); read(t3);        int tmp=LCA(t1,t2);        int tmp2=LCA(t3,tmp);        int c=dep[t1]+dep[t2]-2*dep[tmp];        if(tmp2!=tmp)             printf("%d %d\n",tmp,dep[tmp]+dep[t3]-2*dep[tmp2]+c);        else        {            int tmp3=LCA(t1,t3);            int tmp4=LCA(t2,t3);            if(tmp3==tmp)                printf("%d %d\n",tmp4,c+dep[t3]-dep[tmp4]);            else                printf("%d %d\n",tmp3,c+dep[t3]-dep[tmp3]);        }    }    return 0;}
0 0
原创粉丝点击