当前位置: 首页 > news >正文

HDU 2586 How far away ?(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"? 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


题意:

一个村庄有 n 个房子和 n-1 条双向路,每两个房子之间都有一条简单路径。

如今有m次询问。求两房子之间的距离。

PS:

能够用LCA来解,首先找到u, v 两点的lca,然后计算一下距离值就能够了。

计算方法是。记下根结点到随意一点的距离dis[i],

这样ans = dis[u] + dis[v] - 2 * dis[lca(v, v)]了。

这题要用c++交。G++会爆栈!

代码例如以下:看别人的模板(tarjan 离线)

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define maxn 40047
#define maxm 247

struct node
{
    int to,w,next;
} edge[maxn*2];

int n, m;		//点数,询问次数
int head[maxn];
int k;
int fa[maxn];		//父亲结点
int dis[maxn];		//到根节点距离
int vis[maxn];		//是否訪问过
int s[maxm];		//询问起点
int e[maxm];		//询问终点
int lca[maxm];		//LCA(s,e) 近期公共祖先

int find(int x)
{
    if(fa[x]!=x) return fa[x]=find(fa[x]);
    return fa[x];
}

void init()
{
    k = 1;
    memset(head,0,sizeof(head));
    memset(dis,0,sizeof(dis));
    memset(vis,0,sizeof(vis));
}

void add(int u,int v,int w)
{
    edge[k].to = v;
    edge[k].w = w;
    edge[k].next = head[u];
    head[u] = k++;
}

void tarjan(int u)
{
    int i,v;
    fa[u] = u;
    vis[u] = 1;
    for(i = 0; i < m; i++)
    {
        if(e[i]==u && vis[s[i]])
            lca[i] = find(s[i]);	//若询问的两点中有一点已被訪问过。则两点的LCA则为这一点的当前父节点
        if(s[i]==u && vis[e[i]])
            lca[i] = find(e[i]);
    }
    for(i = head[u]; i; i = edge[i].next)
    {
        v = edge[i].to;
        if(!vis[v]) //若没被訪问过
        {
            dis[v] = dis[u]+edge[i].w;//更新距离
            tarjan(v);
            fa[v] = u;//回溯更新父节点
        }
    }
}

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        init();
        scanf("%d%d",&n,&m);
        int u, v, w;
        for(int i = 0; i < n-1; i++)
        {
            scanf("%d%d%d",&u,&v,&w);
            add(u,v,w);
            add(v,u,w);
        }
        for(int i = 0; i < m; i++)
        {
            scanf("%d%d",&s[i],&e[i]);
        }
        tarjan(1);

        for(int i = 0; i < m; i++)
        {
            printf("%d\n",dis[s[i]]+dis[e[i]]-2*dis[lca[i]]);//两点距离为根节点到两点距离之和-根节点到LCA距离*2
        }
    }
    return 0;
}

(ST在线算法 转)

#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 dp[2*N][M];  //这个数组记得开到2*N,由于遍历后序列长度为2*n-1
bool vis[N];
struct edge
{
    int u,v,w,next;
} e[2*N];
int tot,head[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++;
}
int ver[2*N],R[2*N],first[N],dir[N];
//ver:节点编号 R:深度 first:点编号位置 dir:距离
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 n)
{
    for(int i=1; i<=n; i++)
        dp[i][0] = i;
    for(int j=1; (1<<j)<=n; j++)
    {
        for(int i=1; i+(1<<j)-1<=n; i++)
        {
            int a = dp[i][j-1] , b = dp[i+(1<<(j-1))][j-1];
            dp[i][j] = R[a]<R[b]?a:b;
        }
    }
}
//中间部分是交叉的。
int RMQ(int l,int r)
{
    int k=0;
    while((1<<(k+1))<=r-l+1)
        k++;
    int a = dp[l][k], b = dp[r-(1<<k)+1][k]; //保存的是编号
    return R[a]<R[b]?a: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()
{
    //freopen("Input.txt","r",stdin);
    //freopen("Out.txt","w",stdout);
    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("节点ver "); for(int i=1; i<=2*n-1; i++) printf("%d ",ver[i]); cout << endl;
        printf("深度R "); for(int i=1; i<=2*n-1; i++) printf("%d ",R[i]);   cout << endl;
        printf("首位first "); for(int i=1; i<=n; i++) printf("%d ",first[i]);    cout << endl;
        printf("距离dir "); for(int i=1; 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("%d\n",dir[u] + dir[v] - 2*dir[lca]);
        }
    }
    return 0;
}



相关文章:

  • Mocha BSM产品亮点——报告管理
  • Spring-data-jpa详解,全方位介绍。
  • 互联网DNS存在重大漏洞 黑客可能控制网络流量
  • 基于 POI 封装 ExcelUtil 精简的 Excel 导入导出
  • 发布Web服务器上的虚拟主机:ISA2006系列之十一
  • NFS部署及优化(二)
  • java枚举与.net中的枚举区别
  • 在Hibernate中配置多对多连接表
  • ionic2 自定义cordova插件开发以及使用 (Android)
  • 语录十八
  • 什么样的_BUG_会让你目瞪口呆?
  • C#编程利器之二:结构与枚举(Structure and enumeration)
  • 基础搜索算法的常见题型
  • Memcache安装详解
  • Adobe Premiere-DV采集视频格式常识
  • JS 中的深拷贝与浅拷贝
  • 【干货分享】SpringCloud微服务架构分布式组件如何共享session对象
  • ES6系统学习----从Apollo Client看解构赋值
  • Iterator 和 for...of 循环
  • Java 最常见的 200+ 面试题:面试必备
  • javascript从右向左截取指定位数字符的3种方法
  • JavaScript新鲜事·第5期
  • Python - 闭包Closure
  • scala基础语法(二)
  • vue 配置sass、scss全局变量
  • webpack4 一点通
  • 从0实现一个tiny react(三)生命周期
  • 代理模式
  • 好的网址,关于.net 4.0 ,vs 2010
  • 马上搞懂 GeoJSON
  • 前端之React实战:创建跨平台的项目架构
  • 深度学习在携程攻略社区的应用
  • 什么软件可以剪辑音乐?
  • Nginx惊现漏洞 百万网站面临“拖库”风险
  • !$boo在php中什么意思,php前戏
  • #Java第九次作业--输入输出流和文件操作
  • #每天一道面试题# 什么是MySQL的回表查询
  • (8)Linux使用C语言读取proc/stat等cpu使用数据
  • (C语言)共用体union的用法举例
  • (Matalb分类预测)GA-BP遗传算法优化BP神经网络的多维分类预测
  • (动手学习深度学习)第13章 计算机视觉---图像增广与微调
  • (读书笔记)Javascript高级程序设计---ECMAScript基础
  • (算法)Travel Information Center
  • (转)nsfocus-绿盟科技笔试题目
  • (转)详解PHP处理密码的几种方式
  • (轉貼) 2008 Altera 亞洲創新大賽 台灣學生成果傲視全球 [照片花絮] (SOC) (News)
  • ***微信公众号支付+微信H5支付+微信扫码支付+小程序支付+APP微信支付解决方案总结...
  • *p=a是把a的值赋给p,p=a是把a的地址赋给p。
  • .mat 文件的加载与创建 矩阵变图像? ∈ Matlab 使用笔记
  • .Net core 6.0 升8.0
  • .NET/C# 使用反射注册事件
  • .Net程序猿乐Android发展---(10)框架布局FrameLayout
  • .NET委托:一个关于C#的睡前故事
  • @RequestMapping-占位符映射
  • [android] 切换界面的通用处理