数据结构-树-C语言-PTA-File Transfer

Data Structures and Algorithms (English)

7-8 File Transfer (PTA测试通过)

#include <stdio.h>

#define MaxSize 100000

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

void Initialization(SetType S, int N) {
	for (int i = 0; i < N; i++) S[i] = -1;
}

/*
@program 路径压缩方式查找根
*/
ElementType Find(SetType S, ElementType X) {
	if (S[X]<0) {
		return X;
	}
	else {
		return S[X] = Find(S, S[X]);
	}
}

/*
@program 根据树的高度连接
*/
void Union_s(SetType S, SetName Root1, SetName Root2) {
	if (S[Root2]<S[Root1]) S[Root1] = Root2;
	else if (S[Root1] == S[Root2]){
	  S[Root1]--;
		S[Root2] = Root1;
	}
}

/*
@program 根据树的规模连接,即树有几个节点
*/
void Union(SetType S, SetName Root1, SetName Root2) {
	if (S[Root2]<S[Root1]){
	  S[Root2] += S[Root1];
	  S[Root1]=Root2;
	}else{
	  S[Root1] += S[Root2];
	  S[Root2]=Root1;
	}
}

/*
@program 连接两台机子
*/
void Input_connections(SetType S) {
	ElementType u, v;
	SetName Root1, Root2;
	if (scanf("%d %d\n", &u, &v));
	Root1 = Find(S, u - 1);
	Root2 = Find(S, v - 1);
	if (Root1 != Root2) Union(S, Root1, Root2);
}

/*
@program 检查两台机子是否连接
*/
void Check_connections(SetType S) {
	ElementType u, v;
	SetName Root1, Root2;
	if (scanf("%d %d\n", &u, &v));
	Root1 = Find(S, u - 1);
	Root2 = Find(S, v - 1);
	if (Root1 == Root2) printf("yes\n");
	else printf("no\n");
}

/*
@program 检查整个局域网
*/
void Check_network(SetType S, int n) {
	int i, counter = 0;
	for (i = 0; i < n; i++) {
		if (S[i] < 0) counter++;
	}
	if (counter == 1) printf("The network is connected.\n");
	else printf("There are %d components.\n", counter);
}

int main() {
	SetType S;
	int N;
	if (scanf("%d", &N));
	Initialization(S, N);
	char in;
	do {
		//scanf()加if防止报warning错误
		if (scanf("%c", &in));
		switch (in) {
		case 'I':Input_connections(S); break;
		case 'C':Check_connections(S); break;
		case 'S':Check_network(S, N); break;
		}
	} while (in != 'S');
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40925226/article/details/83449247