代码随想录算法训练营第五十五天 | 图论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;
}
相关推荐
仙俊红44 分钟前
LeetCode每日一题,20250914
算法·leetcode·职场和发展
风中的微尘7 小时前
39.网络流入门
开发语言·网络·c++·算法
西红柿维生素8 小时前
JVM相关总结
java·jvm·算法
ChillJavaGuy10 小时前
常见限流算法详解与对比
java·算法·限流算法
sali-tec10 小时前
C# 基于halcon的视觉工作流-章34-环状测量
开发语言·图像处理·算法·计算机视觉·c#
你怎么知道我是队长11 小时前
C语言---循环结构
c语言·开发语言·算法
艾醒11 小时前
大模型面试题剖析:RAG中的文本分割策略
人工智能·算法
纪元A梦13 小时前
贪心算法应用:K-Means++初始化详解
算法·贪心算法·kmeans
_不会dp不改名_14 小时前
leetcode_21 合并两个有序链表
算法·leetcode·链表
mark-puls14 小时前
C语言打印爱心
c语言·开发语言·算法