【codevs1036】商务旅行,LCA练习

商务旅行
时间限制: 1 s
空间限制: 128000 KB
题目等级 : 钻石 Diamond
题解
题目描述 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
写在前面:无


思路:纯LCA,但为什么我每次写RMQ都感觉又臭又长
代码:

#include
#include
#include
#include
#include
using namespace std;
int n,m,tot,ans,first[60010],deep[30010],pos[30010],num[60010],father[60010][20],dis[60010];
bool flag[30010];
struct os
{
    int fa,son,next,w;
}a[60010];
void add(int x,int y)
{
    tot++;
    a[tot].fa=x;
    a[tot].son=y;
    a[tot].w=1;
    a[tot].next=first[x];
    first[x]=tot;
}
void dfs(int x,int y)
{
    deep[x]=y;
    num[++num[0]]=x;
    pos[x]=num[0];
    father[num[0]][0]=x;
    int k=first[x];
    while (k!=0)
    {
        if (!flag[a[k].son])
        {
            flag[a[k].son]=1;
            dis[a[k].son]=dis[x]+a[k].w;
            dfs(a[k].son,y+1);
            num[++num[0]]=x; 
            father[num[0]][0]=x;
        }
        k=a[k].next;
    }
}
main()
{
    scanf("%d",&n);
    int x,y;
    for (int i=1;i<=n-1;i++) scanf("%d%d",&x,&y),add(x,y),add(y,x);
    flag[1]=1;
    dfs(1,0);
    for (int j=1;j<=log2(num[0]);j++)
    for (int i=1;i<=num[0]-(1<
    {
        x=father[i][j-1];y=father[i+(1<<(j-1))][j-1];
        if (deep[x]>deep[y]) father[i][j]=y;
        else father[i][j]=x;
    }
    scanf("%d",&m);
    int begin=1,end;
    for (int i=1;i<=m;i++)
    {
        scanf("%d",&end);
        int pos1=pos[begin],pos2=pos[end],t;
        if (pos1>pos2) swap(pos1,pos2);
        int mid=log2(pos2-pos1+1);
        x=father[pos1][mid],y=father[pos2-(1<
        if (deep[x]
        else t=y;
        ans+=(dis[begin]+dis[end]-2*dis[t]); 
        begin=end;
    }
    printf("%d",ans);
}

你可能感兴趣的:(【codevs1036】商务旅行,LCA练习)