代码随想录算法训练营第五十五天 | 图论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;
}
相关推荐
大鱼>2 分钟前
AI+快递分拣:视觉识别+自动分拣+异常检测
人工智能·深度学习·算法·机器学习
想要成为糕糕手4 分钟前
238. 除了自身以外数组的乘积 — 面试向深度解析
javascript·算法·面试
浩瀚地学16 分钟前
【面试算法笔记】0105-数组-螺旋矩阵
java·开发语言·笔记·算法·面试
Hesionberger1 小时前
动态规划与二分法破解最长递增子序列
java·数据结构·python·算法·leetcode
imuliuliang1 小时前
关于Kruskal 算法在图优化问题中的扩展应用7
算法
老约家的可汗1 小时前
Linux中基础IO
linux·服务器·算法
满怀冰雪2 小时前
第29篇-状态压缩DP-当状态很多时如何降维优化
java·算法·动态规划
令狐掌门2 小时前
2026华为OD面试题020:日志文件异常检测
算法·leetcode·华为od
炸薯条!2 小时前
从零开始学C++(4) --类和对象
开发语言·c++·算法
haluhalu.2 小时前
prompts.chat:07-few-shot-prompting
人工智能·算法