您的位置:首页 > 其它

codevs 1036 商务旅行 题解报告

2016-10-18 09:37 363 查看
继续我的刷题之路;;;

题目描述 Description

某首都城市的商人要经常到各城镇去做生意,他们按自己的路线去做,目的是为了更好的节约时间。

假设有N个城镇,首都编号为1,商人从首都出发,其他各城镇之间都有道路连接,任意两个城镇之间如果有直连道路,在他们之间行驶需要花费单位时间。该国公路网络发达,从首都出发能到达任意一个城镇,并且公路网络不会存在环。

你的任务是帮助该商人计算一下他的最短旅行时间。

输入描述 Input Description

输入文件中的第一行有一个整数N,1<=n<=30 000,为城镇的数目。下面N-1行,每行由两个整数a 和b (1<=a, b<=n; a<>b)组成,表示城镇a和城镇b有公路连接。在第N+1行为一个整数M,下面的M行,每行有该商人需要顺次经过的各城镇编号。

输出描述 Output Description

在输出文件中输出该商人旅行的最短时间。

样例输入 Sample Input

5

1 2

1 5

3 5

4 5

4

1

3

2

5

样例输出 Sample Output

7

数据范围及提示 Data Size & Hint

读题可知,在一棵树上以一定的顺序走,求最短路径。

可以肯定,在树上两点之间的最短路径就是两点各自走到他们的LCA 的距离和;

所以,对于m个点;

只需要求出第i,i-1 个点的LCA

过程中维护距离,

最后加和即可。

代码如下:::、

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<stack>
#include<cstdlib>
#include<string>
#include<bitset>
#include<iomanip>
#include<deque>
#define INF 1000000000
#define fi first
#define se second
#define N 100005
#define P 1000000007
#define debug(x) cerr<<#x<<"="<<x<<endl
#define MP(x,y) make_pair(x,y)
using namespace std;
int n,m;
int h[N],v[N],next[N],p=0,d[N],f[N],w[N],l[N],j[N][15],ww[N][15],deep
;
bool vv
;
void add(int a,int b)
{
p++;
v[p]=b;
next[p]=h[a];
h[a]=p;
}
inline int get_num()
{
int num = 0;
char c;
bool flag = false;
while ((c = getchar()) == ' ' || c == '\n' || c == '\r');
if (c == '-') flag = true;
else num = c - '0';
while (isdigit(c = getchar()))
num = num * 10 + c - '0';
return (flag ? -1 : 1) * num;
}  //忽略上面这一大堆没用的东西。。。。
void dfs(int x,int s)
{
deep[x]=s;
for(int i=1;(1<<i)<s;i++)
{
j[x][i]=j[j[x][i-1]][i-1];
}
int pp=h[x];
while(pp)
{
if(vv[v[pp]])
{
pp=next[pp];
continue;
}
vv[v[pp]]=1;
j[v[pp]][0]=x;
dfs(v[pp],s+1);
pp=next[pp];
}
}
int LCA(int x,int y)
{
int ans=0;
if(deep[y]>deep[x])
{
int kk=y;
y=x;
x=kk;
}
for(int i=15;i>=0;i--)
{
if((deep[x]-(1<<i))>=deep[y])
{
ans+=(1<<i);
x=j[x][i];
}
}
if(x==y)return ans;
for(int i=15;i>=0;i--)
{
if(j[x][i]!=j[y][i]&&deep[x]-(1<<i)>=1)
{
ans+=(1<<i);
ans+=(1<<i);
x=j[x][i];
y=j[y][i];
}
}
ans+=2;
return ans;
}
int main()
{
cin>>n;
for(int i=1;i<n;i++)
{
int q,w;
cin>>q>>w;
add(q,w);
add(w,q);
}

vv[1]=1;
dfs(1,1);
cin>>m;
int l=1;
int sum=0;
for(int i=1;i<=m;i++)
{
int q;
cin>>q;
sum+=LCA(l,q);
l=q;
}
cout<<sum;
}


噫,,水题。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  noip codevs LCA 倍增