代码随想录算法训练营第五十五天 | 图论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;
}
相关推荐
apcipot_rain30 分钟前
计科八股20260616(2)/面经——线性代数对称阵求n次幂、概率论最大似然估计
算法
cici158741 小时前
彩色图像模糊增强(Fuzzy Enhancement)MATLAB 实现
开发语言·算法·matlab
宝贝儿好1 小时前
【LLM】第二章:HuggingFace入门学习
人工智能·深度学习·神经网络·学习·算法·自然语言处理
凌波粒1 小时前
LeetCode--491.递增子序列(回溯算法)
数据结构·算法·leetcode
啵啵啵鱼1 小时前
数组---完
算法·排序算法
嘿黑嘿呦2 小时前
chap 8排序
算法·蓝桥杯·排序算法·软件工程
richdata2 小时前
需求预测终极指南:零售商品预测方法、算法与AI实践
人工智能·算法·零售
隔窗听雨眠2 小时前
C语言函数递归从入门到精通(下):性能优化与工程实践
c语言·算法·性能优化
退休倒计时2 小时前
【每日一题】LeetCode 146. LRU 缓存 TypeScript
算法·leetcode·缓存·typescript
珊瑚里的鱼2 小时前
【递归】汉诺塔
算法·深度优先