您的位置:首页 > 其它

多个电脑是否连通 ~

2017-07-31 20:43 155 查看
//5   表示 待链接的计算机 个数//C 3 2   表示检查 计算机 3 2 连通状态//I 3 2   如果未连通 则 连通 3 2 两计算机//C 1 5//I 4 5//I 2 4//C 3 5//S   结束 并判断 有几个连通集
#include<stdio.h>#include<stdlib.h>#define MaxSize 10typedef int ElementType;typedef int SetName;typedef ElementType SetType[MaxSize]; //定义整形数组// 普通 的 Find操作  最坏为 O(N^2)//SetName Find(SetType S, ElementType X)//	{//		for(; S[X] >= 0 ; X = S[X]);//		return X;//	}SetName Find(SetType S, ElementType X) // 递归  实现  路径压缩{if(S[X] < 0)return X;else{return S[X] = Find(S, S[X]); //通往根节点路上的节点最终全部直接指向根节点}}//   按秩归并   (按照元素个数)
void Union(SetType S, SetName Root1, SetName Root2){if(S[Root1] < S[Root2]){S[Root1] += S[Root2];S[Root2] = Root1;}else{S[Root2] += S[Root1];S[Root1] = Root2;}}// 按秩归并 (按照树高归并)void Union2(SetType S, SetName Root1, SetName Root2){if(S[Root1] > S[Root2]){S[Root1] = Root2;}else {if(S[Root1] == S[Root2])S[Root1]--;//当两树等高时S[Root2] = Root1;}}//   初始化  开始各节点均不连通 并把高度(或者说是元素个数)  均置为 1   负号表示根节点
void Initialize(SetType S, int N){int i;for(i = 1; i <= N; i++){S[i] = -1;}}	
void Input_connection(SetType S){ElementType u, v;SetName Root1, Root2;scanf("%d %d\n",&u,&v);Root1 = Find(S, u);Root2 = Find(S, v);if(Root1 == Root2)return;else{Union(S, Root1, Root2);}}void check_connection(SetType S){ElementType u, v;SetName Root1, Root2;scanf("%d %d\n",&u,&v); //注意scanf  读取 格式Root1 = Find(S, u);Root2 = Find(S, v);if(Root1 == Root2){printf("Yes\n");}elseprintf("No\n");}void check_network(SetType S, int n){int cnt = 0;int i;for(i = 0; i < n; i++ ){if(S[i] < 0)cnt++;}if(cnt == 1)printf("The network is connected\n");else{printf("There are %d components.\n",cnt);}}int main(){SetType S;int N;char in;scanf("%d",&N);Initialize(S, N);do{scanf("%c",&in);switch(in){case 'I':Input_connection(S);break;case 'C':check_connection(S);break;case 'S':check_network(S, N);break;}}while(in != 'S');return 0;}	
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  printf typedef