#include <stdio.h>
#define Max 1001
int Father[Max];//记录某点的 父节点
int Ranki[Max];//秩 记录总共有多少个节点
//查找父节点
int FindFather(int Child)
{
if(Father[Child] == Child)return Child;//返回最高父节点
else return FindFather(Father[Child]);//一直找 父亲的父亲
}
//获取冗余个数
int GetAnswer(int m,int n)
{
int A[n],B[n];//A[i] - B[i] 记录一组关系
int i,sum = 0;
for(i = 0;i < n;i++)
scanf("%d%d",&A[i],&B[i]);
//开始将 所有父节点都置为自己 秩都为1
for(i = 0;i < m;i++)
{
Father[i] = i;
Ranki[i] = 1;
}
for(i = 0;i < n;i++)
{
//获取 A[i] 与 B[i] 的最高父节点
int SetA = FindFather(A[i]);
int SetB = FindFather(B[i]);
//如果他俩的父节点 相等
if(SetA == SetB)sum++;
else
{ //谁的权大 认谁做父亲
//当权相等的时候 默认A的父亲是B的父亲
if(Ranki[SetA] >= Ranki[SetB])
{
Father[SetB] = SetA;
Ranki[SetA] += Ranki[SetB];
}
else
{
Father[SetA] = SetB;
Ranki[SetB] += Ranki[SetA];
}
}
}
return sum;
}
int main(int argc, char const *argv[])
{
int m,n;//人的个数 关系数量
scanf("%d%d",&m,&n);
int Answer = GetAnswer(m,n);
printf("%d\n",Answer);
return 0;
}
/*
6 7
1 2
3 4
4 6
5 3
2 5
1 6
2 4
*/
王道考研 ++++ 并查集(C语言 对应题目--冗余关系)
猜你喜欢
转载自blog.csdn.net/WX_1218639030/article/details/98105301
今日推荐
周排行