日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

zoj3195 联通树上三个点的路径长

發布時間:2024/8/26 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 zoj3195 联通树上三个点的路径长 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

輸出有個坑,兩個月之前就沒對,,今天又被坑了一次

求聯通樹上三個點的路徑長度,只要求兩兩點對的最短路徑,加起來除以二即可

#include<iostream> #include<cstring> #include<cstdio> #include<queue> using namespace std; #define maxn 50005 #define DEG 20 struct Edge{int to,next,w; }edge[maxn*2]; int head[maxn],tot; inline void addedge(int u,int v,int w){edge[tot].to=v;edge[tot].next=head[u];edge[tot].w=w;head[u]=tot++; } int deg[maxn],depth[maxn],fa[maxn][DEG]; int flag[maxn]; void bfs(int root){queue<int> que;deg[root]=depth[root]=0;fa[root][0]=root;que.push(root);while(!que.empty()){int tmp=que.front();que.pop();for(int i=1;i<DEG;i++)fa[tmp][i]=fa[fa[tmp][i-1]][i-1];for(int i=head[tmp];i!=-1;i=edge[i].next){int v=edge[i].to;if(v==fa[tmp][0]) continue;deg[v]=deg[tmp]+1;depth[v]=depth[tmp]+edge[i].w;fa[v][0]=tmp;que.push(v);}} } int query(int u,int v){if(deg[u]>deg[v]) swap(u,v);int hu=deg[u],hv=deg[v],tu=u,tv=v;for(int det=hv-hu,i=0;det;det>>=1,i++)if(det&1) tv=fa[tv][i];if(tu==tv) return tu;for(int i=DEG-1;i>=0;i--){if(fa[tu][i]==fa[tv][i])continue;tu=fa[tu][i];tv=fa[tv][i];}return fa[tu][0]; } void init(){tot=0;memset(head,-1,sizeof head);memset(depth,0,sizeof depth);memset(deg,0,sizeof deg); } int main(){int n,q,u,v,w;int flagg=0;while(~scanf("%d",&n)){init();for(int i=1;i<n;i++){scanf("%d%d%d",&u,&v,&w);addedge(u,v,w);addedge(v,u,w);flag[v]=1;}int root;for(int i=0;i<n;i++) if(!flag[i]){root=i;break;}bfs(root);if(flagg) putchar('\n');else flagg=1;scanf("%d",&q);int a,b,c;while(q--){scanf("%d%d%d",&a,&b,&c);int tmp1=query(a,b);int dis1=depth[a]+depth[b]-depth[tmp1]*2;int tmp2=query(b,c);int dis2=depth[b]+depth[c]-depth[tmp2]*2;int tmp3=query(a,c);int dis3=depth[a]+depth[c]-depth[tmp3]*2;printf("%d\n",(dis1+dis2+dis3)/2);}} }

?

轉載于:https://www.cnblogs.com/zsben991126/p/10017047.html

總結

以上是生活随笔為你收集整理的zoj3195 联通树上三个点的路径长的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。