Language:
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 |
题意:给一个n个点,m条边构成无向树,边有权值,有k次询问,每次询问u,v的距离。
思路:
解法一:离线lca(tarjan法)
对于询问(u,v),在tarjan的时候记录d[ ],即结点到根的距离,然后求出u,v的lca,然后用d[ u ] + d[ v ] - 2 * d[ lca ] 求出询问,详见代码:
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
const int MAXN=100000+100;
int n,m,k,edge_cnt;
int head[MAXN],fa[MAXN],vis[MAXN],d[MAXN],ans[MAXN];
struct Edge
{
int v,w;
int next;
}edge[2*MAXN];
struct node
{
int v;
int id;
};
vector<node>G[MAXN];
void init()
{
edge_cnt=0;
memset(head,-1,sizeof(head));
for(int i=1;i<=n;i++)
vis[i]=d[i]=0,fa[i]=i,G[i].clear();
}
void addedge(int u,int v,int w)
{
edge[edge_cnt].v=v;
edge[edge_cnt].w=w;
edge[edge_cnt].next=head[u];
head[u]=edge_cnt++;
}
int findset(int x)
{
return fa[x]==x ? x: fa[x]=findset(fa[x]);
}
void tarjan(int u,int f)
{
for(int i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].v,w=edge[i].w;
if(v==f)
continue;
d[v]=d[u]+w;
tarjan(v,u);
}
vis[u]=1;
for(int i=0;i<G[u].size();i++)
{
node x=G[u][i];
int id=x.id,v=x.v;
if(!vis[v])
continue;
int lca=findset(v);
ans[id]=d[u]+d[v]-2*d[lca];
}
fa[u]=f;
}
int main()
{
//freopen("text.txt","r",stdin);
while(~scanf("%d%d",&n,&m))
{
int u,v,w;
char s[5];
init();
for(int i=1;i<=m;i++)
{
scanf("%d%d%d%s",&u,&v,&w,s);
addedge(u,v,w); addedge(v,u,w);
}
scanf("%d",&k);
for(int i=1;i<=k;i++)
{
scanf("%d%d",&u,&v);
node x;
x.v=v; x.id=i;
G[u].push_back(x);
x.v=u;
G[v].push_back(x);
}
tarjan(1,1);
for(int i=1;i<=k;i++)
printf("%d\n",ans[i]);
}
return 0;
}