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≤104), 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);
}
}
上一篇: 画图工具怎么修改图片中的文字?
下一篇: 马超入蜀后郁郁寡欢的真正原因是什么?