05-树8 File Transfer

We have a network of computers and a list of bi-directional connections. Each of these connections allows a file transfer from one computer to another. Is it possible to send a file from any computer on the network to any other?

#include <iostream>
#include<cstdlib>
using namespace std;

#define MaxSize 10000

typedef int ElementType;
typedef int SetName;
typedef ElementType SetType[MaxSize];

void Initialization(SetType S, int N);
void Input_Connection(SetType S);
void Check_Connection(SetType S);
void Check_Network(SetType S, int N);

int main()
{
	SetType S;
	char in;
	int N;
	cin >> N;
	Initialization(S, N);
	do {
		cin >> 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;
}

//压缩路径
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;
	}
}

//所有节点初始化为-1
void Initialization(SetType S, int N)
{
	int i;
	for (i = 0; i <= N; i++) {
		S[i] = -1;
	}
}

void Input_Connection(SetType S)
{
	ElementType c1, c2;
	SetName Root1, Root2;
	cin >> c1 >> c2;
	Root1 = Find(S, c1 - 1);		//读写从1开始,数组从0开始
	Root2 = Find(S, c2 - 1);
	if (Root1 != Root2) {			//不同根说明未连接
		Union(S, Root1, Root2);
	}
}

void Check_Connection(SetType S)
{
	ElementType c1, c2;
	SetName Root1, Root2;
	cin >> c1 >> c2;
	Root1 = Find(S, c1 - 1);
	Root2 = Find(S, c2 - 1);
	if (Root1 == Root2) {			//同根,已连接
		cout << "yes" << endl;
	}
	else {
		cout << "no" << endl;
	}
}

void Check_Network(SetType S, int N)
{
	int cnt = 0, i;
	for (i = 0; i < N; i++) {
		if (S[i] < 0) cnt++;		//检查根节点个数
	}
	if (cnt == 1) {
		cout << "The network is connected." << endl;
	}
	else {
		cout << "There are " << cnt << " components." << endl;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值