代码随想录算法训练营第五十五天 | 图论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;
}
相关推荐
mit6.8249 分钟前
dijk|tire+floyd+dp %
算法
独自破碎E24 分钟前
【总和拆分 + 双变量遍历】LCR_012_寻找数组的中心下标
数据结构·算法
WBluuue24 分钟前
Codeforces 1076 Div3(ABCDEFG)
c++·算法
u01092727135 分钟前
模板编译期排序算法
开发语言·c++·算法
GIS瞧葩菜44 分钟前
Cesium 轴拖拽 + 旋转圈拖拽 核心数学知识
人工智能·算法·机器学习
m0_686041611 小时前
C++中的适配器模式变体
开发语言·c++·算法
txzrxz1 小时前
结构体排序,双指针,单调栈
数据结构·算法·双指针算法·单调栈·结构体排序
AndrewHZ1 小时前
【AI黑话日日新】什么是AI智能体?
人工智能·算法·语言模型·大模型·llm·ai智能体
wWYy.1 小时前
算法:二叉树最大路径和
数据结构·算法
葱明撅腚1 小时前
利用Python挖掘城市数据
python·算法·gis·聚类