本文主要是介绍【CODEVS1036】商务旅行【LCA】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目大题:
题目链接:http://codevs.cn/problem/1036/
给出一棵树和一些要求按顺序到达的点,一开始在点 1 1 1,求走完这些点要花费多少(一条边花费 1 1 1)
思路:
L C A LCA LCA模板题。
假设现在在点 x x x,要到达点 y y y,那么很明显所需要的花费就是 d e p [ x ] + d e p [ y ] − 2 × d e p [ l c a ( x , y ) ] dep[x]+dep[y]-2\times dep[lca(x,y)] dep[x]+dep[y]−2×dep[lca(x,y)]
累加即可。
众所周知, L C A LCA LCA时间复杂度 O ( n l o g n ) O(nlogn) O(nlogn)
代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
#define N 30100
#define LG 20
using namespace std;int n,f[N][LG+1],head[N],dep[N],ans,m,tot;struct edge
{int to,next;
}e[N*2];void add(int from,int to)
{e[++tot].to=to;e[tot].next=head[from];head[from]=tot;
}void dfs(int x,int fa)
{f[x][0]=fa; //f[x][k]表示点x的2^k祖先dep[x]=dep[fa]+1; //深度for (int i=1;i<=LG;i++)f[x][i]=f[f[x][i-1]][i-1];for (int i=head[x];~i;i=e[i].next)if (e[i].to!=fa)dfs(e[i].to,x);
}int lca(int x,int y)
{if (dep[x]<dep[y]) swap(x,y);for (int i=LG;i>=0;i--) //先跳到同一层if (dep[f[x][i]]>=dep[y]) x=f[x][i];if (x==y) return x;for (int i=LG;i>=0;i--) //一起往上跳if (f[x][i]!=f[y][i]){x=f[x][i];y=f[y][i];}return f[x][0];
}int main()
{memset(head,-1,sizeof(head));scanf("%d",&n);int x,y;for (int i=1;i<n;i++){scanf("%d%d",&x,&y);add(x,y);add(y,x);}int now=1;dfs(1,0);scanf("%d",&m);for (int i=1;i<=m;i++){scanf("%d",&x);ans=ans+dep[now]+dep[x]-2*dep[lca(now,x)];now=x;}printf("%d\n",ans);return 0;
}
这篇关于【CODEVS1036】商务旅行【LCA】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!