Connections between cities(LCA + 并查集)

本文探讨了在战后城市重建中如何通过算法确定不同城市间最短物资运输路径的问题。利用LCA与并查集的方法,解决了在部分道路被毁情况下城市间的连通性及最短路径计算。

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

Connections between cities

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5067    Accepted Submission(s): 1410


Problem Description
After World War X, a lot of cities have been seriously damaged, and we need to rebuild those cities. However, some materials needed can only be produced in certain places. So we need to transport these materials from city to city. For most of roads had been totally destroyed during the war, there might be no path between two cities, no circle exists as well.
Now, your task comes. After giving you the condition of the roads, we want to know if there exists a path between any two cities. If the answer is yes, output the shortest path between them.
 

 

Input
Input consists of multiple problem instances.For each instance, first line contains three integers n, m and c, 2<=n<=10000, 0<=m<10000, 1<=c<=1000000. n represents the number of cities numbered from 1 to n. Following m lines, each line has three integers i, j and k, represent a road between city i and city j, with length k. Last c lines, two integers i, j each line, indicates a query of city i and city j.
 

 

Output
For each problem instance, one line for each query. If no path between two cities, output “Not connected”, otherwise output the length of the shortest path between them.
 

 

Sample Input
5 3 2
1 3 2
2 4 3
5 2 3
1 4
4 5
 

 

Sample Output

 

Not connected
6
Hint
Hint Huge input, scanf recommended.

 

      题意:

      给出 N 个结点,M 条边,K 个询问。输出每个询问间的距离,如果不能达到的话则输出 Not connected。

 

      思路:

      LCA + 并查集。用并查集判断是否在同一棵上,在同一棵树上则用 LCA 算出距离即可。

 

      AC:

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int NMAX = 10010;
const int EMAX = 10000 * 5;

int n, m, c;

int root[NMAX];

int ind;
int fir[NMAX], next[EMAX], w[EMAX], v[EMAX];

int ans;
int id[NMAX], vs[NMAX * 3], dep[NMAX * 3], dis[NMAX];
bool vis[NMAX];

int dp[NMAX * 3][50];

void init () {
    ind = ans = 0;
    memset(fir, -1, sizeof(fir));
    memset(vis, 0, sizeof(vis));
    for (int i = 1; i <= n; ++i)
        root[i] = i;
}

void add_edge (int f, int t, int val) {
    v[ind] = t;
    w[ind] = val;
    next[ind] = fir[f];
    fir[f] = ind;
    ++ind;
}

int Find (int x) {
    return x == root[x] ? x : root[x] = Find(root[x]);
}

void merge_tree (int a, int b) {
    int A = Find(a);
    int B = Find(b);
    if (A != B) root[A] = B;
}

bool que_tree (int a, int b) {
    if (Find(a) == Find(b)) return true;
    return false;
}

void dfs (int x, int d) {
    id[x] = ans;
    vs[ans] = x;
    dep[ans++] = d;
    vis[x] = 1;

    for (int e = fir[x]; e != -1; e = next[e]) {
        int V = v[e];
        if (!vis[V]) {
            dis[V] = dis[x] + w[e];
            dfs(V, d + 1);
            dep[ans] = d;
            vs[ans++] = x;
        }
    }
}

void RMQ_init () {
    for (int i = 0; i < ans; ++i) dp[i][0] = i;

    for (int j = 1; (1 << j) <= ans; ++j) {
        for (int i = 0; i + (1 << j) < ans; ++i) {
            int a = dp[i][j - 1];
            int b = dp[i + (1 << (j - 1))][j - 1];
            if (dep[a] < dep[b]) dp[i][j] = a;
            else dp[i][j] = b;
        }
    }
}

int RMQ (int L, int R) {
    int len = 0;
    while ((1 << (len + 1)) <= (R - L + 1)) ++len;

    int a = dp[L][len];
    int b = dp[R - (1 << len) + 1][len];

    if (dep[a] < dep[b]) return a;
    return b;
}

int LCA (int a, int b) {
    int L = min(id[a], id[b]);
    int R = max(id[a], id[b]);

    int node = RMQ(L, R);
    return vs[node];
}

int main() {

    while (~scanf("%d%d%d", &n, &m, &c)) {
        init();

        while (m--) {
            int a, b, val;
            scanf("%d%d%d", &a, &b, &val);
            add_edge(a, b, val);
            add_edge(b, a, val);
            merge_tree(a, b);
        }

        for (int i = 1; i <= n; ++i) {
            if (root[i] == i) {
                dis[i] = 0;
                dfs(i, 1);
            }
        }

        RMQ_init();

        while (c--) {
            int a, b;
            scanf("%d%d", &a, &b);
            if (que_tree(a, b)) {
                int c = LCA(a, b);
                printf("%d\n", dis[a] + dis[b] - 2 * dis[c]);
            } else puts("Not connected");
        }
    }

    return 0;
}

 

 

### 并查集算法实现集合问题 以下是基于 JavaScript 的并查集算法代码示例,该代码可以用来解决与集合分组、合并和查询相关的问题: #### 初始化并查集类 ```javascript class UnionFind { constructor(n) { this.parent = Array.from({ length: n }, (_, i) => i); // 初始时每个节点的父节点都是自己 this.rank = Array(n).fill(0); // 用于优化树的高度 } find(x) { // 查找操作:找到 x 所属集合的根节点,并进行路径压缩 if (this.parent[x] !== x) { this.parent[x] = this.find(this.parent[x]); } return this.parent[x]; } union(x, y) { // 合并操作:将两个元素所在的集合合并 let rootX = this.find(x); let rootY = this.find(y); if (rootX === rootY) return; // 如果已经在同一个集合中,则无需处理 if (this.rank[rootX] > this.rank[rootY]) { this.parent[rootY] = rootX; } else if (this.rank[rootX] < this.rank[rootY]) { this.parent[rootX] = rootY; } else { this.parent[rootY] = rootX; this.rank[rootX]++; } } countSets() { // 统计当前有多少个独立的集合 const roots = new Set(); for (let i = 0; i < this.parent.length; i++) { roots.add(this.find(i)); } return roots.size; } } ``` 上述代码实现了并查集的核心功能 `find` 和 `union` 方法。其中 `find` 方法负责查找某个元素所属集合的代表元(即根节点),并通过路径压缩优化性能;而 `union` 方法则负责将两个不同集合中的元素合并成一个集合。 #### 使用场景举例 假设我们需要解决一个问题:给定一组城市之间的连接关系,判断这些城市被划分为多少个连通区域。可以通过如下方式调用上面定义好的 `UnionFind` 类来解决问题[^2]: ```javascript function connectedCities(connections, numCities) { const uf = new UnionFind(numCities); // 将所有相连的城市加入同一集合 connections.forEach(([cityA, cityB]) => { uf.union(cityA - 1, cityB - 1); // 假设城市编号从1开始,因此减去1适配数组索引 }); // 返回最终的集合数量 return uf.countSets(); } // 测试数据 const citiesConnections = [ [1, 2], [2, 3], [4, 5] ]; console.log(connectedCities(citiesConnections, 5)); // 输出应为 2 ``` 此函数接收两参数——城市的连接列表以及总共有几个城市。它会创建一个新的并查集实例并将每一对已知相互连接的城市放入相同的集合里。最后计算剩余的不同集合数目作为结果返回。 ### 总结 通过以上方法能够有效利用并查集这一高效工具快速求解涉及动态变化集合归属情况下的各类复杂度较高的组合型难题[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值