hdu 2586

LCA模板题

How far away ?

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

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<k<=40000).The
houses are labeled from 1 to n.
  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

Recommend

lcy   |   We have carefully selected several similar problems for you:  3486 2874 2888 3234 2818

题意:给一个无根树,有q个询问,每个询问两个点,问两点的距离。求出  lca = LCA(X,Y) , 然后  dir[x] + dir[y] - 2 * dir[lca]

dir[u]表示点u到树根的距离

下面两份代码都可以通过HDU的C++和G++,都不存在爆栈问题,网上很多人说会爆栈,加了申请系统栈语句,其实不用,而且好想比赛中不允许使用的

Tarjan算法跑得更快些,C++ 15ms,  G++ 50ms  左右, RMQ大概60ms

在线算法:LCA转化为RMQ

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
//#pragma comment(linker, "/STACK:102400000,102400000") //不需要申请系统栈
const int N = 40010;
const int M = 25;

int _pow[M];
int tot,head[N],ver[2*N],R[2*N],first[N],dir[N];
int dp[2*N][M];  //这个数组记得开到2*N,因为遍历后序列长度为2*n-1
bool vis[N];
struct edge
{
    int u,v,w,next;
}e[2*N];

inline void add(int u ,int v ,int w ,int &k)
{
    e[k].u = u; e[k].v = v; e[k].w = w;
    e[k].next = head[u]; head[u] = k++;
    u = u^v; v = u^v; u = u^v;
    e[k].u = u; e[k].v = v; e[k].w = w;
    e[k].next = head[u]; head[u] = k++;
}

void dfs(int u ,int dep)
{
    vis[u] = true; ver[++tot] = u; first[u] = tot; R[tot] = dep;
    for(int k=head[u]; k!=-1; k=e[k].next)
        if( !vis[e[k].v] )
        {
            int v = e[k].v , w = e[k].w;
            dir[v] = dir[u] + w;
            dfs(v,dep+1);
            ver[++tot] = u; R[tot] = dep;
        }
}

void ST(int len)
{
    int K = (int)(log((double)len) / log(2.0));
    for(int i=1; i<=len; i++) dp[i][0] = i;
    for(int j=1; j<=K; j++)
        for(int i=1; i+_pow[j]-1<=len; i++)
        {
            int a = dp[i][j-1] , b = dp[i+_pow[j-1]][j-1];
            if(R[a] < R[b]) dp[i][j] = a;
            else            dp[i][j] = b;
        }
}

int RMQ(int x ,int y)
{
    int K = (int)(log((double)(y-x+1)) / log(2.0));
    int a = dp[x][K] , b = dp[y-_pow[K]+1][K];
    if(R[a] < R[b]) return a;
    else            return b;
}

int LCA(int u ,int v)
{
    int x = first[u] , y = first[v];
    if(x > y) swap(x,y);
    int res = RMQ(x,y);
    return ver[res];
}

int main()
{
    for(int i=0; i<M; i++) _pow[i] = (1<<i);
    int cas;
    scanf("%d",&cas);
    while(cas--)
    {
        int n,q,num = 0;
        scanf("%d%d",&n,&q);
        memset(head,-1,sizeof(head));
        memset(vis,false,sizeof(vis));
        for(int i=1; i<n; i++)
        {
            int u,v,w;
            scanf("%d%d%d",&u,&v,&w);
            add(u,v,w,num);
        }
        tot = 0; dir[1] = 0;
        dfs(1,1);
        /*
        printf("节点 "); for(int i=1; i<=2*n-1; i++) printf("%d ",ver[i]); cout << endl;
        printf("深度 "); for(int i=1; i<=2*n-1; i++) printf("%d ",R[i]);   cout << endl;
        printf("首位 "); for(int i=0; i<n; i++) printf("%d ",first[i]);    cout << endl;
        printf("距离 "); for(int i=0; i<n; i++) printf("%d ",dir[i]);      cout << endl;
        */
        ST(2*n-1);
        while(q--)
        {
            int u,v;
            scanf("%d%d",&u,&v);
            int lca = LCA(u,v);
//            printf("lca = %d\n",lca);
            printf("%d\n",dir[u] + dir[v] - 2*dir[lca]);
        }
    }
    return 0;
}

离线算法:Tarjan算法解决

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 40010;
const int M = 410;

int head[N],__head[N];
struct edge{
    int u,v,w,next;
}e[2*N];
struct ask{
    int u,v,lca,next;
}ea[M];
int dir[N],fa[N],ance[N];
bool vis[N];

inline void add_edge(int u,int v,int w,int &k)
{
    e[k].u = u; e[k].v = v; e[k].w = w;
    e[k].next = head[u]; head[u] = k++;
    u = u^v; v = u^v; u = u^v;
    e[k].u = u; e[k].v = v; e[k].w = w;
    e[k].next = head[u]; head[u] = k++;
}

inline void add_ask(int u ,int v ,int &k)
{
    ea[k].u = u; ea[k].v = v; ea[k].lca = -1;
    ea[k].next = __head[u]; __head[u] = k++;
    u = u^v; v = u^v; u = u^v;
    ea[k].u = u; ea[k].v = v; ea[k].lca = -1;
    ea[k].next = __head[u]; __head[u] = k++;
}

int Find(int x)
{
    return x == fa[x] ? x : fa[x] = Find(fa[x]);
}
void Union(int u ,int v)
{
    fa[v] = fa[u];  //可写为  fa[Find(v)] = fa[u];
}

void Tarjan(int u)
{
    vis[u] = true;
    ance[u] = fa[u] = u; //课写为 ance[Find(u)] = fa[u] = u;
    for(int k=head[u]; k!=-1; k=e[k].next)
        if( !vis[e[k].v] )
        {
            int v = e[k].v , w = e[k].w;
            dir[v] = dir[u] + w;
            Tarjan(v);
            Union(u,v);
            //ance[Find(u)] = u;  //可写为ance[u] = u;  //甚至不要这个语句都行
        }
    for(int k=__head[u]; k!=-1; k=ea[k].next)
        if( vis[ea[k].v] )
        {
            int v = ea[k].v;
            ea[k].lca = ea[k^1].lca = ance[Find(v)];
        }
}

int main()
{
    int cas,n,q,tot;
    scanf("%d",&cas);
    while(cas--)
    {
        scanf("%d%d",&n,&q);
        memset(head,-1,sizeof(head));
        memset(__head,-1,sizeof(__head));
        tot = 0;
        for(int i=1; i<n; i++)
        {
            int u,v,w;
            scanf("%d%d%d",&u,&v,&w);
            add_edge(u,v,w,tot);
        }
        tot = 0;
        for(int i=0; i<q; i++)
        {
            int u,v;
            scanf("%d%d",&u,&v);
            add_ask(u,v,tot);
        }
        memset(vis,0,sizeof(vis));
        dir[1] = 0;
        Tarjan(1);
        for(int i=0; i<q; i++)
        {
            int s = i * 2 , u = ea[s].u , v = ea[s].v , lca = ea[s].lca;
            printf("%d\n",dir[u] + dir[v] - 2*dir[lca]);
        }
    }
    return 0;
}
时间: 2024-10-29 04:19:20

hdu 2586的相关文章

LCA(最近公共祖先)--tarjan离线算法 hdu 2586

HDU 2586 How far away ? Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 11320    Accepted Submission(s): 4119 Problem Description There are n houses in the village and some bidirectional roads c

HDU - 2586 - How far away ?

先上题目: How far away ? Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4936    Accepted Submission(s): 1866 Problem Description There are n houses in the village and some bidirectional roads conne

HDU 2586 How far away?

http://acm.hdu.edu.cn/showproblem.php?pid=2586 题意:给定一个图,有M个询问.每一次询问为询问u,v两个点的距离为多少? 题解:LCA问题. 1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 #include <cstdlib> 5 #include <cmath> 6 #include <string> 7

HDU 2586 How far away ? (LCA最近公共祖先)

题目地址:HDU 2586 LCA第一发. 纯模板题. 偷懒用的vector,结果一直爆栈.把G++改成C++就过了.. 代码如下: #include <iostream> #include <string.h> #include <math.h> #include <queue> #include <algorithm> #include <stdlib.h> #include <map> #include <se

HDU 2586 + HDU 4912 最近公共祖先

先给个LCA模板 HDU 1330(LCA模板) #include <cstdio> #include <cstring> #define N 40005 struct Edge{ int x,y,d,ne; }; Edge e[N*2],e2[N*2]; int be[N],be2[N],all,all2,n,m; bool vis[N]; int fa[N]; int ancestor[N][3]; int dis[N]; void add(int x, int y, int

hdu 2586 LCA模板题(离线算法)

http://acm.hdu.edu.cn/showproblem.php?pid=2586 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&quo

最近公共祖先(lca) hdu 2586

hdu 2586 How far away ? 题目大意:给定n-1条边构成一棵树,无向的:和m个询问,对于每一个询问按顺序回答. 结题思路:lca算法算出最近公共祖先,然后dis[u]+dis[v]-2*dis[father](father是u,v的最近公共祖先),小trick是在构造询问树的时候把权值设成询问对应的输入顺序 #include <iostream> #include <cstdio> #include <cstring> #include <al

HDU 2586 LCA-Tarjan

还是LCA-tarjan算法,跟POJ 1330做法基本类似,只是这个题目要求输出两个点的最短距离,其实利用LCA的性质,就是 两个点分别到最近公共祖先的距离之和 一开始本来想用并查集把路径长度给找出来,但是不太好处理,原因是我刚好找到的这个点还没有加入到并查集中,(因为还没回溯上去),如果马上就合并,我还得把父亲传下来,还破坏了原有算法的结构(在孩子这里就进行了并查集合并操作),会产生奇怪的结果... 有个很简便又机智的方法,就是在dfs的过程中 一边记录从rt到下面的点的距离dis,假设 A

hdu 2586 How far away ?倍增LCA

hdu 2586 How far away ?倍增LCA 题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=2586 思路: 针对询问次数多的时候,采取倍增求取LCA,同时跟新距离数组 因为 \(2^{16} > 40000\) 所以所以表示祖先的数组dp[][]第二维取到16即可 就这道题来说,与比较tarjan比较,稍快一点 代码: #include <iostream> #include <algorithm> #includ

HDU 2586 LCA模板题

题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=2586 题目大意:在一个无向树上,求一条链权和. 解题思路: 0 | 1 /   \ 2      3 设dist[i]为i到根0的链和,求法(Dfs过程中dist[v]=dist[u]+e[i].w) 对于树中任意两点形成的链,可以通过LCA最近公共祖先剖分. 比如2->3,就可以经过LCA点1:  2->1->3 链和=dist[u]+dist[v]-2*dist[LCA[u,v]] (