当前位置:网站首页>连通图(并查集)
连通图(并查集)
2022-07-17 12:49:00 【好像几块钱】
int find(int x) //找根结点(找教主)
{
if(pre[x] != find(x)) pre[x] = find(pre[x]);
return pre[x];
}
例题:并查集
给定一个无向图和其中的所有边,判断这个图是否所有顶点都是连通的。
输入格式
输入包含若干组数据。
每组数据第一行包含两个整数 nn 和 mm,表示无向图的点和边数。
接下来 mm 行,每行包含两个整数 x,yx,y,表示点 xx 和点 yy 相连。
点的编号从 11 到 nn。
图中可能存在重边和自环。
输出格式
每组数据输出一行,一个结果,如果所有顶点都是连通的,输出
YES,否则输出NO。数据范围
输入最多包含 1010 组数据。
1≤n≤10001≤n≤1000,
1≤m≤50001≤m≤5000,
1≤x,y≤n1≤x,y≤n输入样例:
4 3 1 2 2 3 3 2 3 2 1 2 2 3输出样例:
NO YES
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=1010;
int pre[N];
int find(int x)
{
if(pre[x]!=x) pre[x]=find(pre[x]);
return pre[x];
}
int main()
{
int n,m,a,b;
while(cin>>n>>m)
{
for(int i=1;i<=n;i++) pre[i]=i;
while(m--)
{
cin>>a>>b;
pre[find(a)]=find(b);
}
bool res=true;
for(int i=2;i<=n;i++)
{
if(find(i)!=find(1))
res=false;
}
if(res) puts("YES");
else puts("NO");
}
return 0;
}2022/7/11
边栏推荐
- c语言指针的有关总结
- 因果学习将开启下一代AI浪潮?九章云极DataCanvas正式发布YLearn因果学习开源项目
- LVI-SAM:激光-IMU-相机紧耦合建图
- How to use SVG to make text effects arranged along any path
- TS解决引入插件的类型文件不存在的问题
- Autojs learning - multi function treasure chest - medium
- Know what it is, and know why, JS object creation and inheritance
- Bazel use tutorial to
- Attachment handling of SAP Fiori
- 开发第一个Flink应用
猜你喜欢

string类的介绍及模拟实现

C serialport configuration and attribute understanding

How to realize the association between interfaces in JMeter?

智能存储柜控制系统设计及仿真

HCIA rip experiment 7.11

看一看这丑恶嘴脸 | MathWorks Account Unavailable - Technical Issue

Zhongke Panyun - Cyberspace Security packet capture topic b.pcap

Takeout ordering system based on wechat applet

yarn(cdh)中的虚拟cpu和内存

YARN环境中应用程序JAR包冲突问题的分析及解决
随机推荐
【Makefile】关于makefile使用上的一些备忘
yarn(cdh)中的虚拟cpu和内存
AutoJs学习-多功能宝箱-下
电商销售数据分析与预测(日期数据统计、按天统计、按月统计)
R language uses the KAP function of epidisplay package to calculate the proportion of calculation consistency of paired contingency tables and the value of kappa statistics, and uses xtabs function to
idea展示服务端口--service
Detailed explanation of C language custom types
Map遍历 key-value 的4种方法
Figure an introduction to the interpretable method of neural network and a code example of gnnexplainer interpreting prediction
Studio 3T unlimited trial
[PostgreSQL] PostgreSQL 15 optimizes distinct
机器学习模型的评估方法
c语言指针的有关总结
AutoJs学习-动态解密
开发第一个Flink应用
架构实战营|模块7
从预测到决策,九章云极DataCanvas推出YLearn因果学习开源项目
Virtual CPU and memory in yarn (CDH)
知其然,而知其所以然,JS 对象创建与继承
The new energy track has high risks, so please pay attention to safety