代码随想录算法训练营第五十五天 | 图论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;
}
相关推荐
牛客企业服务9 分钟前
2025年AI面试推荐榜单,数字化招聘转型优选
人工智能·python·算法·面试·职场和发展·金融·求职招聘
糖葫芦君1 小时前
Policy Gradient【强化学习的数学原理】
算法
向阳@向远方3 小时前
第二章 简单程序设计
开发语言·c++·算法
github_czy3 小时前
RRF (Reciprocal Rank Fusion) 排序算法详解
算法·排序算法
许愿与你永世安宁4 小时前
力扣343 整数拆分
数据结构·算法·leetcode
爱coding的橙子4 小时前
每日算法刷题Day42 7.5:leetcode前缀和3道题,用时2h
算法·leetcode·职场和发展
满分观察网友z4 小时前
从一次手滑,我洞悉了用户输入的所有可能性(3330. 找到初始输入字符串 I)
算法
YuTaoShao5 小时前
【LeetCode 热题 100】73. 矩阵置零——(解法二)空间复杂度 O(1)
java·算法·leetcode·矩阵
Heartoxx5 小时前
c语言-指针(数组)练习2
c语言·数据结构·算法
大熊背5 小时前
图像处理专业书籍以及网络资源总结
人工智能·算法·microsoft