代码随想录算法训练营第五十五天 | 图论part05

107. 寻找存在的路径

只需要判断是否联通,不需要知道具体路径或者路径数量,可以使用并查集。

cpp 复制代码
// project1.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include <iostream>
#include <vector>
using namespace std;

void init(vector<int> &father) {
    for (int i = 0; i < father.size(); ++i) {
        father[i] = i;
    }
}

int find(vector<int>& father, int u) {
    if (father[u] == u) return u;
    return father[u] = find(father, father[u]);
}

int isSame(vector<int>& father, int u, int v) {
    u = find(father, u);
    v = find(father, v);
    return u == v;
}

void join(vector<int>& father, int u, int v) {
    u = find(father, u);
    v = find(father, v);
    if (u == v) return;
    father[v] = u;
}
int main()
{
    int n, m, u, v, source, destination;
    cin >> n >> m;
    vector<int> father(n + 1, 0);
    init(father);
    while (m--) {
        cin >> u >> v;
        join(father, u, v);
    }
    cin >> source >> destination;
    if (isSame(father, source, destination))
        cout << 1 << endl;
    else
    {
        cout << 0 << endl;
    }
    return 0;
}
相关推荐
luj_176813 分钟前
大航海时代:沉浸式财商实战沙盒
c语言·开发语言·网络·经验分享·算法
Navigator_Z35 分钟前
LeetCode //C - 1200. Minimum Absolute Difference
c语言·算法·leetcode
wabs6661 小时前
关于字符串【力扣344.反转字符串的思考】
数据结构·算法·leetcode
民乐团扒谱机2 小时前
【微实验】谐波乘积谱(HPS)算法深度解析:原理、数学与代码实现
开发语言·人工智能·python·算法·语音识别·音乐
Nil2082 小时前
leetcode 73矩阵置0
算法·leetcode·矩阵
忍冬k3 小时前
DeepSeek harness安装指南
java·开发语言·数据结构·c++·算法
何以解忧,唯有..3 小时前
预订酒店问题
算法
No8g攻城狮4 小时前
【算法】什么是 DFS 与 BFS 及他们的区别
算法·深度优先·宽度优先
旖旎夜光4 小时前
LeetCode 1658:将 x 减到 0 的最小操作数(滑动窗口) —— 题解
数据结构·c++·算法·leetcode·滑动窗口
zww89491114 小时前
家政派单系统实战指南:从需求分析到智能调度算法落地
算法·需求分析