当前位置: 代码迷 >> 综合 >> Distance Queries 【LCA倍增 求最短路】
  详细解决方案

Distance Queries 【LCA倍增 求最短路】

热度:34   发布时间:2023-11-10 05:54:59.0

Farmer John’s cows refused to run in his marathon since he chose a path much too long for their leisurely lifestyle. He therefore wants to find a path of a more reasonable length. The input to this problem consists of the same input as in “Navigation Nightmare”,followed by a line containing a single integer K, followed by K “distance queries”. Each distance query is a line of input containing two integers, giving the numbers of two farms between which FJ is interested in computing distance (measured in the length of the roads along the path between the two farms). Please answer FJ’s distance queries as quickly as possible!
Input
* Lines 1..1+M: Same format as “Navigation Nightmare”

  • Line 2+M: A single integer, K. 1 <= K <= 10,000

  • Lines 3+M..2+M+K: Each line corresponds to a distance query and contains the indices of two farms.
    Output

  • Lines 1..K: For each distance query, output on a single line an integer giving the appropriate distance.
    Sample Input
    7 6
    1 6 13 E
    6 3 9 E
    3 5 7 S
    4 1 3 N
    2 4 20 W
    4 7 2 S
    3
    1 6
    1 4
    2 6
    Sample Output
    13
    3
    36
    Hint
    Farms 2 and 6 are 20+3+13=36 apart.

题中的那个方向不用管,就是一个求lca的裸题。
最近学了倍增,练习练习
代码

#include<string.h>
#include<stdio.h>
#include<iostream>
#include<math.h>
#define LL long long
const int MAXN = 100000+10;
const int inf =0x3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-8;
using namespace std;
inline int read(){int x=0,f=1;char ch=getchar();while(ch<'0'||ch>'9'){ if(ch=='-') f=-1;ch =getchar();}while(ch>='0'&&ch<='9') {x=x*10+ch-'0' ;ch=getchar();}return x*f;
}
/*--------------------------------*/
struct Edge {int from,to,val,next;
}edge[MAXN<<2];
int head[MAXN],top;
int n,m;
void init(){memset(head,-1,sizeof(head));top=0;
}
void addedge(int a,int b,int c){Edge e={a,b,c,head[a]};edge[top]=e;head[a]=top++;
}
void getmap(){int a,b,c;char k;while(m--){scanf("%d %d %d %c",&a,&b,&c,&k);addedge(a,b,c);addedge(b,a,c);}
}
int fa[MAXN][20],depth[MAXN];
int dist[MAXN];
void dfs(int now,int par){fa[now][0]=par;for(int i=1;i<20;i++){fa[now][i]=fa[fa[now][i-1]][i-1];}for(int i=head[now];i!=-1;i=edge[i].next){Edge e=edge[i];if(e.to!=par){dist[e.to]=dist[now]+e.val;depth[e.to]=depth[now]+1;dfs(e.to,now);}}
}
int lca(int a,int b){if(depth[a]<depth[b]) swap(a,b);for(int i=19;i>=0;i--){if(depth[fa[a][i]]>=depth[b]){a=fa[a][i];}}if(a==b) return b;for(int i=19;i>=0;i--){if(fa[a][i]!=fa[b][i]){a=fa[a][i];b=fa[b][i];}}return fa[b][0];
}
void solve(){depth[1]=0;dist[1]=0;dfs(1,-1);int q;int l,r;cin>>q;while(q--){scanf("%d%d",&l,&r);printf("%d\n",dist[l]+dist[r]-2*dist[lca(l,r)]);}
}
int main(){while(~scanf("%d%d",&n,&m)){init();getmap();solve();}
}
  相关解决方案