Codeforces Gym - 101808K(倍增LCA最近公共祖先)

本文介绍了一种使用LCA算法和并查集解决带有环的图中多次最短路径查询的方法。通过预处理得到LCA和最短路径,避免了每次查询时的重复计算,实现了高效查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

题意:

给 n 个点,n 条边(3  <= n <= 100000),q 次询问,每次求 u 到 v 之间的最短路。没有重边和自环。

题解:

显然 O(n2logn) 是会超时的。由于只给了n条边,那么去掉一条边就是一棵树了。这时可以用LCA求解。我看这位大佬的代码学的

用并查集即可将成环的一条边从图中除去。之后的每次查询只需要判断经过这条边和不经过这条边哪个更小即可。具体看代码。

代码:

#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <string>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <bitset>
using namespace std;

typedef long long ll;
#define int ll
#define INF 0x3f3f3f3f3f3f3f3f
#define MAXM 32 + 10
#define MAXN 300000 + 10
const ll mod = 1e9 + 7;
#define P pair<int, int>
#define fir first
#define sec second

int t, n, q;
vector<P> G[MAXN];
int father[MAXN];
int dis[MAXN], dep[MAXN];
int gfa[MAXM][MAXN];

int get_root(int x)
{
    if(x == father[x]) return x;
    return father[x] = get_root(father[x]);
}

void dfs(int now, int fa, int d)
{
    gfa[0][now] = fa;
    dep[now] = d;
    for(int i = 0; i < G[now].size(); i ++) {
        if(G[now][i].sec != fa) {
            dis[G[now][i].sec] = dis[now] + G[now][i].fir;
            dfs(G[now][i].sec, now, d + 1);
        }
    }
}

void init()
{
    dfs(1, -1, 0);
    for(int k = 0; k + 1 < 32; k ++) {
        for(int v = 1; v <= n; v ++) {
            if(gfa[k][v] == -1) gfa[k+1][v] = -1;
            else gfa[k+1][v] = gfa[k][gfa[k][v]];
        }
    }
}

int LCA(int u, int v)
{
    if(dep[u] > dep[v]) swap(u, v);
    for(int k = 0; k < 32; k ++) {
        if((dep[v] - dep[u]) >> k & 1)
            v = gfa[k][v];
    }
    if(u == v) return u;
    for(int k = 31; k >= 0; k --) {
        if(gfa[k][u] != gfa[k][v]) {
            u = gfa[k][u];
            v = gfa[k][v];
        }
    }
    return gfa[0][u];
}

int get_dis(int u, int v)
{
    return dis[u] + dis[v] - 2 * dis[LCA(u, v)];
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
    cin >> t;
    while(t --) {
        cin >> n >> q;
        int ru, rv, rx;
        for(int i = 1; i <= n; i ++) {
            father[i] = i;
            G[i].clear();
        }
        for(int i = 0; i < n; i ++) {
            int a, b, x; cin >> a >> b >> x;
            int ra = get_root(a);
            int rb = get_root(b);
            if(ra == rb) {
                ru = a, rv = b, rx = x;
                continue;
            }
            father[ra] = rb;
            G[a].push_back(P(x, b));
            G[b].push_back(P(x, a));
        }
        init();
        while(q --) {
            int u, v; cin >> u >> v;
            int ans = get_dis(u, v);
            ans = min(ans, get_dis(ru, u) + rx + get_dis(rv, v));
            ans = min(ans, get_dis(ru, v) + rx + get_dis(rv, u));
            cout << ans << endl;
        }
    }
}

/*

The WAM is F**KING interesting .

*/

 

### Codeforces Problem 976C Solution in Python For solving problem 976C on Codeforces using Python, efficiency becomes a critical factor due to strict time limits aimed at distinguishing between efficient and less efficient solutions[^1]. Given these constraints, it is advisable to focus on optimizing algorithms and choosing appropriate data structures. The provided code snippet offers insight into handling string manipulation problems efficiently by customizing comparison logic for sorting elements based on specific criteria[^2]. However, for addressing problem 976C specifically, which involves determining the winner ('A' or 'B') based on frequency counts within given inputs, one can adapt similar principles of optimization but tailored towards counting occurrences directly as shown below: ```python from collections import Counter def determine_winner(): for _ in range(int(input())): count_map = Counter(input().strip()) result = "A" if count_map['A'] > count_map['B'] else "B" print(result) determine_winner() ``` This approach leverages `Counter` from Python’s built-in `collections` module to quickly tally up instances of 'A' versus 'B'. By iterating over multiple test cases through a loop defined by user input, this method ensures that comparisons are made accurately while maintaining performance standards required under tight computational resources[^3]. To further enhance execution speed when working with Python, consider submitting codes via platforms like PyPy instead of traditional interpreters whenever possible since they offer better runtime efficiencies especially important during competitive programming contests where milliseconds matter significantly.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值