poj——1986 Distance Queries
阅读原文时间:2021年04月20日阅读:1

                      Distance Queries

Time Limit: 2000MS

 

Memory Limit: 30000K

Total Submissions: 14392

 

Accepted: 5066

Case Time Limit: 1000MS

Description

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. 

Source

USACO 2004 February

此种类似题目可以直接通过求两节点lca来解决,ans=dis[x]+dis[y]-2*dis[lca(x,y)]

代码:

#include
#include
#include
#include
#include
#define N 51000
using namespace std;
int n,m,x,y,z,t,tot,ans;
int fa[N],dis[N],top[N],deep[N],size[N],head[N];
struct Edge
{
int from,to,dis,next;
}edge[N<<]; int read() { ,f=; char ch=getchar(); ; ch=getchar();} +ch-'; ch=getchar();} return x*f; } int add(int x,int y,int z) { tot++; edge[tot].to=y; edge[tot].dis=z; edge[tot].next=head[x]; head[x]=tot; } int dfs(int x) { size[x]=; deep[x]=deep[fa[x]]+; for(int i=head[x];i;i=edge[i].next) { int to=edge[i].to; if(fa[x]==to) continue; dis[to]=dis[x]+edge[i].dis; fa[to]=x,dfs(to);size[x]+=size[to]; } } int dfs1(int x) { ; if(!top[x]) top[x]=x; for(int i=head[x];i;i=edge[i].next) { int to=edge[i].to; if(fa[x]!=to&&size[t]deep[y]) swap(x,y);
return x;
}
int main()
{
n=read(),m=read();
;i<=m;i++)
{
x=read(),y=read(),z=read();
add(x,y,z),add(y,x,z);
}
dfs(),dfs1();
t=read();
;i<=t;i++)
{
x=read(),y=read();
ans=dis[x]+dis[y]-*dis[lca(x,y)];
printf("%d\n",ans);
}
;
}