Hdu 2874 Connections between cities

Source: Internet
Author: User

Test instructions

City Road no ring not necessarily connected tree to find the shortest distance between two cities imagine a lot of little trees.

Ideas:

LCA offline algorithm Then there is a trick that every time we tarjan a tree not the last tree node has visited and the child all-around to find root well, so we just do do do to do it all the city has been visited all the time, you do this little tree will not affect the other trees

#include <cstdio>#include<cstring>#include<algorithm>using namespacestd;intn,m;Const intN =10005;Const intM =1000005;intf[n],next[2*n],va[2*n],wi[2*N],head[n];intVis[n];intnex[2*m],to[2*M],id[m],head[n],ans[m];intFindintx) {    if(X!=f[x]) f[x]=find (f[x]); returnf[x];}intlen,dis[n],l;voidAddintUintVintW) {Va[len]=v; Wi[len]=W; Next[len]=Head[u]; Head[u]=len++;}voidAdd_x (intUintv) {To[l]=v; NEX[L]=Head[u]; Head[u]=l++;} voidLcaintUintFA) {F[u]=T;  for(inti=head[u];i!=-1; i=Next[i]) {intv=va[i],w=Wi[i]; if(v!=FA) {Dis[v]=dis[u]+W;        LCA (V,U); F[V]=u; }} Vis[u]=1;  for(inti=head[u];i!=-1; i=Nex[i]) {        intv=To[i]; if(Vis[v]) {//puts ("SADASD");ans[i/2]=Find (v); }    }    }intMain () {intK;  while(~SCANF ("%d%d%d",&n,&m,&k)) {Len=l=0; memset (Head,-1,sizeofHead); memset (Head,-1,sizeofhead); for(intI=0; i<m;i++)    {            intu,v,w; scanf ("%d%d%d",&u,&v,&W);        Add (U,V,W);    Add (V,U,W); } dis[1]=0;  for(intI=0; i<k;i++)    {        intu,v; scanf ("%d%d",&u,&v); Id[i]=u;        add_x (U,V);    add_x (V,u); }memset (Vis,0,sizeofvis); Memset (F,0,sizeoff); memset (ans,-1,sizeofans);  for(intI=1; i<=n;i++)if(vis[i]==0) LCA (I,0);  for(intI=0; i<l;i+=2)        {                        intA,b,c; A=To[i]; b=id[i/2]; if(Find (a)!=find (b)) puts ("Not connected"); Else{c=ans[i/2]; printf ("%d\n", dis[a]+dis[b]-2*dis[c]);} }    }}

Hdu 2874 Connections between cities

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.