代码随想录算法训练营第五十五天 | 图论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 分钟前
虫情测报灯图像识别算法实践:小目标检测、粘连计数与飞虱细粒度分类
算法·目标检测·分类
爱读书的小胖31 分钟前
LeetCode 27. 移除元素(C)解题分析
数据结构·算法
科技小E32 分钟前
敏感数据不敢上云训练?本地大模型推理服务器DLTM私有化部署,让训练全程留在企业内网
大数据·算法·自动化
小草cys1 小时前
用 GPT 直接生成可编辑 PPTX 的实操记录,artifact-tool是OpenAICodex环境专用
gpt·算法·pptx
爱读书的小胖1 小时前
Codewars: A Brave New Wordle(C)解题分析
c语言·数据结构·算法
Escalating_xu1 小时前
【数据结构】顺序表的应用:动态通讯录项目与双指针经典算法
c语言·数据结构·算法
其实防守也摸鱼1 小时前
CTF Web 6 题全解 Writeup
linux·sql·学习·算法·安全·ctf·xss
宇明一不急1 小时前
string和byte的相互转换
算法
波力海苔夹心脆6752 小时前
VisionPro 与 VisionMaster 对比(上):软件定位、开发环境与核心视觉工具对照
图像处理·算法·计算机视觉·c#·视觉检测·个人开发·vp9
动词ing2 小时前
【题目练习】盛最多水的容器
算法·目标检测