codevs 1036

7 篇文章 0 订阅
4 篇文章 0 订阅

商务旅行

#include <cstdio>
#include <cmath>
#include <iostream>
#define MAXN 30010

using namespace std;

int n, m, x, y, cnt, ans, ts;
int f[MAXN][22], h[MAXN][22];
int now[MAXN], deep[MAXN];
bool vis[MAXN];

struct E {
    int to, nxt;
}es[MAXN * 2];

void addedge(int a, int b) {
    es[++ cnt].to = b;
    es[cnt].nxt = now[a];
    now[a] = cnt;
}

int read() {
    int f = 1, k = 0;
    char c = getchar();
    while(c < '0' || c > '9') {
        if(c == '-') {
            f = -1;
        }
        c = getchar();
    }
    while(c <= '9' && c >= '0') {
        k = k * 10 + c - '0';
        c = getchar();
    }
    return f * k;
}

void dfs(int a) {
    vis[a] = true;
    for(int i = now[a]; i != 0; i = es[i].nxt) {
        int s = es[i].to;
        if(!vis[s]) {
            deep[s] = deep[a] + 1;
            f[s][0] = a;
            h[s][0] = 1;
            dfs(s);
        }
    }
}

void lca_init() {
    for(int i = 1; i <= ts; i ++) {
        for(int j = 1; j <= n; j ++) {
            f[j][i] = f[f[j][i - 1]][i - 1];
            h[j][i] = h[j][i - 1] * 2;
        }
    }
}

int lca(int a, int b) {
    int ans1 = 0;
    if(deep[a] < deep[b]) {
        swap(a, b);
    }
    for(int i = ts; i >= 0; i -- ) {
        if(deep[f[a][i]] >= deep[b]) {
            ans1 += h[a][i];
            a = f[a][i];
        }
    }
    if(b == a) return ans1;
    for(int i = ts; i >= 0; i --) {
        if(f[a][i] != f[b][i]) {
            ans1 += h[a][i];
            ans1 += h[b][i];
            a = f[a][i];
            b = f[b][i];
        }
    }
    return ans1 + 2;
}
int main() {
    n = read();
    for(int i = 1; i < n; i ++) {
        x = read(), y = read();
        addedge(x, y);
        addedge(y, x);
    }
    ts = (log(n) / log(2));
    deep[1] = 1;
    dfs(1);
    lca_init();
    m = read(), x = read();
    for(int i = 2; i <= m; i ++) {
        y = read();
        ans += lca(x, y);
        x = y;
    }
    printf("%d", ans);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值