HDU2586 How far away ?(树上倍增求LCA)

题目链接

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 25284    Accepted Submission(s): 10051

Problem Description

There are n houses in the village and some bidirectional roads connecting them. Every day peole always like to ask like this "How far is it if I want to go from house A to house B"? Usually it hard to answer. But luckily int this village the answer is always unique, since the roads are built in the way that there is a unique simple path("simple" means you can't visit a place twice) between every two houses. Yout task is to answer all these curious people.

Input

First line is a single integer T(T<=10), indicating the number of test cases.
  For each test case,in the first line there are two numbers n(2<=n<=40000) and m (1<=m<=200),the number of houses and the number of queries. The following n-1 lines each consisting three numbers i,j,k, separated bu a single space, meaning that there is a road connecting house i and house j,with length k(0   Next m lines each has distinct integers i and j, you areato answer the distance between house i and house j.

Output

For each test case,output m lines. Each line represents the answer of the query. Output a bland line after each test case.

Sample Input

2

3 2

1 2 10

3 1 15

1 2

2 3

 

2 2

1 2 100

1 2

2 1

Sample Output

10

25

100

100

Source

ECJTU 2009 Spring Contest

 

题意:在树上查找询问的两个节点u和v的距离。

思路:先把无根树转化为有根树,以1为根节点。dis[i]表示i节点距离根节点1的距离。

#include
using namespace std;

const int N=40010;//节点的个数
const int M=20;//树最大可能深度

struct Node
{
    int v,w;
    Node(int a,int b):v(a),w(b){};
};
vectoredge[N];//edge[u][i].v,从u点出发的第i条边为v
int fa[N][M],depth[N],dis[N],n,m;
//fa[i][j]:i节点向上推移2的j次方的节点
//depth[i]:i节点在树中的深度
//dis[i]:以1节点为根节点,从1节点到i节点的路径距离
void add_edge(int u,int v,int w)
{
    edge[u].push_back(Node(v,w));
}//添加边

void dfs(int u,int root,int d)
{
    int i;
    depth[u]=d;
    fa[u][0]=root;//初始化
    int sz=edge[u].size();
    for(i=0;i=0;i--)
        if((1<=0;i--)//u和v现在已经在一层,他们往上走几层之后祖先序列相同
    {//找到最小的不满足相同序列的点,
        if(fa[u][i]!=fa[v][i])
        {
            u=fa[u][i];
            v=fa[v][i];
        }
    }
    return fa[u][0];//最后,最近公共祖先为找到的点的祖先
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        int i,j,x,y,z;
        scanf("%d%d",&n,&m);
        for(i=1;i<=n;i++)
            edge[i].clear();
        for(i=1;i<=n-1;i++)
        {
            scanf("%d%d%d",&x,&y,&z);
            add_edge(x,y,z);
            add_edge(y,x,z);
        }
        dis[1]=0;
        dfs(1,0,0);
        bz();
        while(m--)
        {
            scanf("%d%d",&x,&y);
            int ans=dis[x]+dis[y]-2*dis[LCA(x,y)];
            printf("%d\n",ans);
        }
    }
    return 0;
}

 

你可能感兴趣的:(数据结构)