欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

poj1986 Distance Queries (lca模板)

程序员文章站 2022-05-27 16:13:29
...

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. 

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<math.h>
#include<stack>
#include<vector>
#include<map>
#define nn 100001
#define mm 500001
#define inff 0x3fffffff
using namespace std;
#pragma comment(linker, "/STACK:102400000,102400000")
int fa[nn],n,m,num,t,num1;
int vis[nn];
int ans[nn];
int sum[nn];
int p[nn],p1[nn];
struct node
{
    int en,next,c;
}e[2*nn],q[2*nn];
int add(int st,int en,int id)
{
    e[num].en=en;e[num].next=p[st];e[num].c=id;p[st]=num++;
}
int add1(int st,int en,int id)
{
    q[num1].en=en;q[num1].next=p1[st];q[num1].c=id;p1[st]=num1++;
}
int init()
{
    memset(p,-1,sizeof(p));
    memset(p1,-1,sizeof(p1));
    memset(vis,0,sizeof(vis));
    for(int i=1;i<=n;i++)
        fa[i]=i;
    num=num1=0;
}
int find(int x)
{
    while(x!=fa[x])
        x=fa[x];
   return x;
}
void dfs(int u,int pre,int val)
{
    sum[u]=val;
    for(int i=p[u];i+1;i=e[i].next)
    {
        int v=e[i].en;
        int c=e[i].c;
        if(v==pre)
            continue;
        dfs(v,u,val+c);
        fa[v]=u;
    }
    for(int i=p1[u];i+1;i=q[i].next)
    {
        int v=q[i].en;
        if(vis[v])
        {
            int c=q[i].c;
            int aim=find(v);
            ans[c]=sum[u]+sum[v]-2*sum[aim];
        }
    }
    vis[u]=1;
}
int main()
{
    int a,b,c;
    char s[10];
   while(~scanf("%d%d",&n,&m))
   {
       init();
       for(int i=1;i<=m;i++)
       {
           scanf("%d%d%d%s",&a,&b,&c,s);
           add(a,b,c);
           add(b,a,c);
       }
       scanf("%d",&t);
       for(int i=1;i<=t;i++)
       {
           scanf("%d%d",&a,&b);
           add1(a,b,i);
           add1(b,a,i);
       }
       dfs(1,-1,0);
       for(int i=1;i<=t;i++)
        printf("%d\n",ans[i]);
   }
}