File Transfer (25分)【C语言】路径压缩

习题讲解视频

题目:

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?

输入格式

Each input file contains one test case. For each test case, the first line contains N (2≤N≤10​4​​), the total number of computers in a network. Each computer in the network is then represented by a positive integer between 1 and N. Then in the following lines, the input is given in the format:
I c1 c2
where I stands for inputting a connection between c1 and c2; or
C c1 c2
where C stands for checking if it is possible to transfer files between c1 and c2; or
S
where S stands for stopping this case.

输出格式

For each C case, print in one line the word “yes” or “no” if it is possible or impossible to transfer files between c1 and c2, respectively. At the end of each case, print in one line “The network is connected.” if there is a path between any pair of computers; or “There are k components.” where k is the number of connected components in this network.

输入样例

5
C 3 2
I 3 2
C 1 5
I 4 5
I 2 4
C 3 5
S

输出样例

no
no
yes
There are 2 components.

算法

集合基本操作

集合的常规存储方式见下图。
关键算法描述
在本题中由于数据对象是1~N 表示的,这时可以使用数组下标直接表示数据对象,利用数组Key值记录父节点下标。这种存储方式加速了Find的查找速度。
在这里插入图片描述

代码实现

int main()
{	
	int N=0;
	scanf("%d",&N);
	int *A=(int*)malloc(sizeof(int)*(N+1));
	int i=0;
	for(i=0;i<=N;i++){
	    A[i]=-1;
	}
	char c;
	int a=0,b=0;
	scanf("\n%c",&c);
	do{
	    switch(c){
	        case 'C':
	            scanf("%d%d",&a,&b);
	            Check(A,a,b);
	            break;
	        case 'I':
	            scanf("%d%d",&a,&b);
	            Union(A,a,b);
	            break;
	    }
	    scanf("\n%c",&c); 
	}while(c!='S');
	Print(A,N);
		return 0;
}		

Find:返回所属集合名字(根节点下标)

int Find(int A[],int X) 
{
	if(A[X]<0)return X;
	return A[X]=Find(A,A[X]);
}

Union:找到a,b元素所属的集合名字,比较集合的规模,然后把小规模(集合元素个数)接到大规模上

 void Union(int A[],int a,int b)
{
	int root1=Find(A,a);
	int root2=Find(A,b);
	if(A[root1]<A[root2]){
		A[root1]=(A[root1]+A[root2]);
		A[root2]=root1;
	}else{
		A[root2]=(A[root1]+A[root2]);
		A[root1]=root2;
	}
}		

其他函数:

void Check(int A[],int a,int b)
{
	int root1=Find(A,a);
	int root2=Find(A,b);
	if(root1!=root2){
	    printf("no\n");
	}else{
	    printf("yes\n");
	}
}
void Print(int A[],int N)
{
	int i=0,count=0;
	for(i=1;i<=N;i++){
	    if(A[i]<0){
	        count++;
	    }
	}
	if(count==1){
	    printf("The network is connected.\n");
	}else{
	    printf("There are %d components.\n",count);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值