案例4-1.7-文件传输-编程题

案例4-1.7-文件传输-编程题

解题代码

#include<stdio.h>
#define MAXN 10000
typedef int set_type[MAXN];
void Initialization(set_type S, int N);
void Input_connection(set_type S);
void Check_connection(set_type S);
void Check_network(set_type S, int N);
int Find(set_type S, int x);
void Union(set_type S, int root1, int root2);
int main()
{
	int N;
	set_type S;
	char in;
	scanf("%d\n", &N);
	Initialization(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;
}
void Initialization(set_type S, int N) {
	int i;
	for (i = 0; i < N; i++) S[i] = -1;
}
void Input_connection(set_type S) {
	int x1, x2;
	scanf("%d %d\n", &x1, &x2);
	int root1 = Find(S, x1-1);
	int root2 = Find(S, x2-1);
	if (root1 != root2) Union(S, root1, root2);
	
}
void Check_connection(set_type S) {
	int x1, x2;
	scanf("%d %d\n", &x1, &x2);
	int root1 = Find(S, x1-1);
	int root2 = Find(S, x2-1);
	if (root1 != root2) printf("no\n");
	else printf("yes\n");
}
void Check_network(set_type S,int N) {
	int counter = 0;
	int i;
	for (i = 0; i < N; i++) {
		if (S[i] < 0) counter++;
	}
	if (counter == 1) printf("The network is connected.");
	else printf("There are %d components.", counter);
}
int Find(set_type S, int x) {
	if (S[x] < 0) return x;
	else return S[x] = Find(S, S[x]);
}
void Union(set_type S, int root1, int root2) {
	if (root1 < root2) {
		S[root1] += S[root2];
		S[root2] = root1;
	}
	else {
		S[root2] += S[root1];
		S[root1] = root2;
	}
}

测试结果

在这里插入图片描述

问题整理

1.第一遍做这题,思路主要来自姥姥。
2.在处理Find(S,x1-1)的映射问题时出现疏漏,希望下次做这道题可以顺利做出来。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值