比赛 寒假集训2 评测结果 AAAAAATTTTTTTTTTTTTT
题目名称 轻重边 最终得分 30
用户昵称 xuyuqing 运行时间 15.946 s
代码语言 C++ 内存使用 13.95 MiB
提交时间 2026-02-25 11:38:29
显示代码纯文本

#include <algorithm>
#include <cstdio>
#include <cstring> 
#include <iostream>
#include <vector>

using namespace std;

const int N = 114514;
const int LOG = 18; 

int t;
int n;
int m;
vector<int> graph[N];
int fa[N][LOG];
int dep[N];
bool num[N];

void dfs (int now, int dad) {
    fa[now][0] = dad;
    dep[now] = dep[dad] + 1;
    for (int i = 1; i < LOG; i++) {
        fa[now][i] = fa[fa[now][i - 1]][i - 1];
    }
    
    for (int i = 0; i < graph[now].size(); i++) {
        if (graph[now][i] == dad) {
            continue;
        }
        dfs (graph[now][i], now);
    }
}

int lca (int u, int v) {
    if (dep[u] < dep[v]) {
        swap (u, v);
    }
    
    for (int i = LOG - 1; i >= 0; i--) {
        if (dep[fa[u][i]] >= dep[v]) {
            u = fa[u][i];
        }
    }
    
    if (u == v) {
        return u;
    }
    
    for (int i = LOG - 1; i >= 0; i--) {
        if (fa[u][i] != fa[v][i]) {
            u = fa[u][i];
            v = fa[v][i];
        }
    }
    
    return fa[u][0];
}

void del (int u, int grand) {
    int t = u;
    while (true) {
        for (int i = 0; i < graph[u].size(); i++) {
            if (graph[u][i] == fa[u][0]) {
                continue;
            }
            num[graph[u][i]] = 0;
        }
        
        if (u == grand) {
            break;
        }
        
        u = fa[u][0];
    }
}

void add (int u, int grand) {
    while (true) {
        num[u] = 1;
        if (u == grand) {
            num[u] = 0;
            break;
        }
        u = fa[u][0];
    }
}

int query (int u, int grand) {
    int ans = 0;
    while (u != grand) {
        ans += num[u];
        u = fa[u][0];
    }
    return ans;
}

int main () {
    
    freopen ("edge.in", "r", stdin);
    freopen ("edge.out", "w", stdout);
    
    cin >> t;
    for (int index = 1; index <= t; index++) {
        cin >> n >> m;
        memset (num, 0, sizeof (num));
        for (int i = 1; i <= n; i++) {
            graph[i].clear();
        }
        
        for (int i = 1; i < n; i++) {
            int u, v;
            cin >> u >> v;
            graph[u].push_back(v);
            graph[v].push_back(u);
        }
        
        dfs (1, 0);
        
        for (int i = 1; i <= m; i++) {
            int opt, a, b;
            cin >> opt >> a >> b;
            
            int c = lca (a, b);
            
            if (opt == 1) {
                del (a, c);
                del (b, c);
                add (a, c);
                add (b, c);
            }
            if (opt == 2) {
                cout << query (a, c) + query (b, c) << endl;
            }
        }
    }
    
    return 0;
}