当前位置:网站首页>连通图(并查集)
连通图(并查集)
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
边栏推荐
- Virtual CPU and memory in yarn (CDH)
- R language uses the aggregate function of epidisplay package to divide numerical variables into different subsets based on factor variables, calculate the summary statistics of each subset, and set na
- opencv 画黑色矩形,并写上序号
- R language uses LM function to build linear regression model, and uses subset function to specify the subset of data set to build regression model (uses subset function to filter the data subset that
- Analysis and solution of application jar package conflict in yarn environment
- VScode+Unity3D的配置
- The new energy track has high risks, so please pay attention to safety
- 机器学习模型的评估方法
- Huawei wireless device configuration intelligent roaming
- NJCTF 2017messager
猜你喜欢

Design of the multi live architecture in different places of the king glory mall

How to solve the problem of cross domain access by Google browser

电商销售数据分析与预测(日期数据统计、按天统计、按月统计)

NJCTF 2017messager

多元线性回归详解

On the structural types of C language

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

C语言自定义类型详解

string类的介绍及模拟实现

二分类学习推广到多分类学习
随机推荐
Design of the multi live architecture in different places of the king glory mall
C serialport configuration and attribute understanding
Develop the first Flink app
如果是用mybatics去访问达梦数据库,相当于完全一样了?因为SQL语法没变。对吧?
从预测到决策,九章云极DataCanvas推出YLearn因果学习开源项目
The new energy track has high risks, so please pay attention to safety
Aike AI frontier promotion (7.17)
圆桌实录:炉边对话——如何在 Web3 实现创新
R language uses the ordinal of epidisplay package or. The display function obtains the summary statistical information of the ordered logistic regression model (the odds ratio and its confidence inter
Autojs learning - Dynamic decryption
华为机试:报文解压缩
Analysis and solution of application jar package conflict in yarn environment
通过中序遍历和前序遍历,后续遍历来构建二叉树
MFC|框架下自绘CEdit控件
无法改变的现状
十分钟从 PyTorch 转 MXNet(转)
JSP based novel writing and creation website
二叉树刷题(二)
yarn(cdh)中的虚拟cpu和内存
B. Accuratelee [double pointer] [substr function]