造轮子博客链接
前引功能介绍
C 表示Check Connection功能 就是是否连通
I 表示Input Connection功能 放入连通者
先输入的数 表示可能最大用户数 提前准备空间
退出后会显示 一共有几个集合
如果是一个 则说明放入的所有对象都是连通的
代码实现
#include <iostream>
#include <vector>
using namespace std;
struct Union_Find
{
private:
int count;
vector<int> u;
public:
Union_Find(int number){count = 0,u = vector<int>(number+1,-1);}
int Print_Count()
{return count;}
int Find(int num)
{
if(u[num]<0) return num;
else
{
u[num] = Find(u[num]);
return u[num];
}
}
void Make_Pairs(int n1,int n2)
{
if(u[n1] == -1 && u[n2] == -1)
{
u[n1] = -2,u[n2] = n1;
++count;
}
else
{
if(u[n1] == -1)
{
int find2 = Find(n2);
u[find2]-=1;
u[n1] = find2;
}
else if(u[n2] == -1)
{
int find1 = Find(n1);
u[find1]-=1;
u[n2] = find1;
}
else
{
int find1 = Find(n1),find2 = Find(n2);
if(find1 != find2)
{
if(u[find1] > u[find2])
{
u[find2] += u[find1];
u[find1] = find2;
}
else
{
u[find1] += u[find2];
u[find2] = find1;
}
--count;
}
}
}
}
bool Read_Pairs()
{
int n1,n2;
cin>>n1>>n2;
if(n1 < 0 || n2< 0) return false;
Make_Pairs(n1,n2);
return true;
}
};
int main()
{
string temp;
int n,n1,n2;
cout<<"this is dynamic connect question ~ "<<endl;
cout<<"the biggest num please input:"<<endl;
cin>>n;
Union_Find u(n);
cout<<endl<<"I 10 9 means inputing connection 10-9~"<<endl;
cout<<"C 10 9 means checking connection 10-9~"<<endl;
cout<<"If have output 'yes' else not output 'no' "<<endl;
cout<<"Please input ur connection pairs (between 0 ~ n) 'q' stop"<<endl;
while(cin>>temp)
{
if(temp == "q" || temp == "Q") break;
else if(temp == "I" || temp == "i")
{
if(!u.Read_Pairs()) cout<<"Input Error!"<<endl;
}
else if(temp == "C" || temp == "c")
{
cin>>n1>>n2;
if(u.Find(n1) == u.Find(n2)) cout<<"yes"<<endl;
else cout<<"no"<<endl;
}
else cout<<"Input Error!"<<endl;
}
if(u.Print_Count() == 1) cout<<"The network is connected."<<endl;
else cout<<"the components are "<<u.Print_Count()<<endl;
return 0;
}
测试Sample1
最大数站点大于等于5即可
C 3 2
I 3 2
C 1 5
I 4 5
I 2 4
C 3 5
q
测试Output1
no
no
yes
The network is connected.
测试Sample2
最大数站点大于等于7即可
C 3 2
I 3 2
C 1 5
I 4 5
I 2 4
C 3 5
I 1 3
C 1 5
C 7 6
I 6 7
q
测试Output2
no
no
yes
yes
no
"the components are 2"