代码随想录算法训练营第五十五天 | 图论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;
}
相关推荐
郝学胜-神的一滴11 分钟前
深度学习入门基石:PyTorch张量核心技术全解析
人工智能·pytorch·python·深度学习·算法·机器学习
Frostnova丶18 分钟前
(10)LeetCode 560. 和为K的子数组
算法·leetcode·哈希算法
AI专业测评22 分钟前
2026年AI写作软件底层技术全景解析:长篇AI写网文的工程化实践与AI消痕算法基准测试
人工智能·算法·ai写作
2401_8845632428 分钟前
高性能日志库C++实现
开发语言·c++·算法
葳_人生_蕤28 分钟前
hot100——226.翻转二叉树
算法
handler0133 分钟前
基础算法:BFS
开发语言·数据结构·c++·学习·算法·宽度优先
2401_8795034133 分钟前
C++中的状态模式实战
开发语言·c++·算法
不当菜鸡的程序媛34 分钟前
神经网络——bias 偏置项(bias term) 或者截距项(intercept term)
人工智能·神经网络·算法
Aawy12034 分钟前
自定义字面量实战
开发语言·c++·算法
无尽的罚坐人生37 分钟前
hot 100 200. 岛屿数量
算法·dfs