Hdu 2874 (LCA)

Source: Internet
Author: User

During the virtual competition, the shortest was to find the shortest path of any two points. No matter how the optimization was done, it timed out. Recently, some tree questions were made. This is the distance from any two points to the nearest common ancestor, first, determine whether China Unicom is connected with the nearest public ancestor by using the Union and difference set. First, construct the image into a pair of tokens,

 

 

 

 


 

#include<string.h>#include<stdio.h>#define N 10010int father[N],dfs[N],n,vis[N],head[N],num,f[N],ans,dis[N];struct edge{int st,ed,next,w;}E[N*2];void addedge(int x,int y,int w){E[num].st=x;E[num].ed=y;E[num].w=w;E[num].next=head[x];head[x]=num++;}int find(int a){if(f[a]!=a)f[a]=find(f[a]);return f[a];}void dfs1(int u){int i,v;vis[u]=1;for(i=head[u];i!=-1;i=E[i].next){v=E[i].ed;if(vis[v]==1)continue;father[v]=u;dfs[v]=dfs[u]+1;dis[v]=E[i].w;dfs1(v);}if(ans<dfs[u])ans=dfs[u];}int LCA(int x,int y){int sum=0;while(dfs[x]>dfs[y]){sum+=dis[x];x=father[x];}while(dfs[y]>dfs[x]){sum+=dis[y];y=father[y];}while(x!=y){sum+=(dis[x]+dis[y]);x=father[x];y=father[y];}return sum;}int main(){int i,j,k,x,y,m,ans,w;while(scanf("%d%d%d",&n,&m,&k)!=-1){memset(head,-1,sizeof(head));num=0;for(i=1;i<=n;i++)f[i]=i;for(i=0;i<m;i++){scanf("%d%d%d",&x,&y,&w);addedge(x,y,w);addedge(y,x,w);x=find(x);y=find(y);if(x!=y)f[x]=find(y);}memset(vis,0,sizeof(vis));ans=1;for(i=1;i<=n;i++){if(vis[i]==0){dis[i]=0;dfs[i]=ans;father[i]=i;dfs1(i);ans++;}}while(k--){scanf("%d%d",&x,&y);if(find(x)!=find(y)){printf("Not connected\n");continue;}j=LCA(x,y);printf("%d\n",j);}}return 0;}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.