代码随想录算法训练营第五十五天 | 图论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;
}
相关推荐
磊灬泽3 分钟前
【Linux驱动开发】PWM子系统-servo
linux·运维·算法
wan5555cn27 分钟前
当代社会情绪分类及其改善方向深度解析
大数据·人工智能·笔记·深度学习·算法·生活
陈增林1 小时前
基于 PyQt5 的多算法视频关键帧提取工具
开发语言·qt·算法
C嘎嘎嵌入式开发3 小时前
【机器学习算法篇】K-近邻算法
算法·机器学习·近邻算法
小L~~~3 小时前
2025吉比特-游戏引擎开发-一面复盘
数据结构·算法·游戏引擎
程序猿Eason3 小时前
U587038 背包 题解
c++·算法·动态规划
potato_may3 小时前
第18讲:C语言内存函数
c语言·数据结构·算法
dingzd954 小时前
TikTok推荐算法快速解析
算法·机器学习·web3·facebook·推荐算法·tiktok·instagram
仰泳的熊猫4 小时前
LeetCode:95. 不同的二叉搜索树 II
数据结构·c++·算法·leetcode