7-8-File Transfer-编程题

7-8-File Transfer-编程题

解题代码

#include<stdio.h>
#define MAXN 10000
typedef int set[MAXN];
void Initialization(set S, int N);
void Input_connection(set S);
void Check_connection(set S);
void Check_networks(set S, int N);
int Find(set S, int x);
void Union(set S, int root1, int root2);
int main()
{
	int N, i;
	set S;
	scanf("%d\n", &N);
	Initialization(S,N);
	char in;
	do {
		scanf("%c", &in);
		switch (in)
		{
		case 'I':Input_connection(S); break;
		case 'C':Check_connection(S); break;
		case 'S':Check_networks(S,N); break;
		}
	} while (in != 'S');
	return 0;
}
void Initialization(set S, int N) {
	int i;
	for (i = 0; i < N; i++) S[i] = -1;
}
void Input_connection(set S) {
	int x1, x2, root1, root2;
	scanf("%d %d\n", &x1, &x2);
	root1 = Find(S, x1 - 1);
	root2 = Find(S, x2 - 1);
	if (root1 != root2) Union(S, root1, root2);
}
void Check_connection(set S) {
	int x1, x2, root1, root2;
	scanf("%d %d\n", &x1, &x2);
	root1 = Find(S, x1 - 1);
	root2 = Find(S, x2 - 1);
	if (root1 != root2) printf("no\n");
	else printf("yes\n");
}
void Check_networks(set 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.");
	else printf("There are %d components.",counter);
}
int Find(set S, int x) {
	if (S[x] < 0) return x;
	else return S[x] = Find(S, S[x]);
}
void Union(set S, int root1, int root2) {
	if (root1 == root2) return;
	if (S[root1] < S[root2]) {
		S[root1] += S[root2];
		S[root2] = root1;
	}
	else {
		S[root2] += S[root1];
		S[root1] = root2;
	}
}

测试结果

在这里插入图片描述

问题整理

1.基础题。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值