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?
Input Specification:
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.
Output Specification:
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.
Sample Input 1:
5
C 3 2
I 3 2
C 1 5
I 4 5
I 2 4
C 3 5
S
Sample Output 1:
no
no
yes
There are 2 components.
Sample Input 2:
5
C 3 2
I 3 2
C 1 5
I 4 5
I 2 4
C 3 5
I 1 3
C 1 5
S
Sample Output 2:
no
no
yes
yes
The network is connected.
思路:本題的關鍵點是按秩歸併和路徑壓縮,關於這兩點在MOOC上老師有很詳細的解釋。
#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
int S[10001];
int N;
int Find(int S[],int i)
{
if(S[i] < 0)
{
return i;
}
else
return S[i] = Find(S,S[i]);/*不斷的找父結點,一直找到根結點,然後再把每個父結點指向根結點*/
}
void check(int S[])
{
int root1,root2;
int a, b;
scanf("%d %d",&a,&b);
root1 = Find(S,a-1);
root2 = Find(S,b-1);
if(root1 == root2)
{
printf("yes\n");
}
else
printf("no\n");
}
void Union(int S[],int root1,int root2)
{
if(S[root2] < S[root1])
{
S[root2] += S[root1];
S[root1] = root2;
}
else
{
S[root1] += S[root2];
S[root2] = root1;
}
}
void Insert(int S[])
{
int root1,root2;
int a, b;
scanf("%d %d",&a,&b);
root1 = Find(S,a-1);
root2 = Find(S,b-1);
if(root1 != root2)
{
Union(S,root1,root2);
}
}
int main(void)
{
char ch;
int count = 0;
scanf("%d",&N);
for(int i = 0; i < N; i++)/*初始化令每個結點都是根結點*/
{
S[i] = -1;
}
while(1)
{
scanf("%s",&ch);
if(ch == 'C')
{
check(S);
}
else if(ch == 'I')
{
Insert(S);
}
else if(ch == 'S')
{
break;
}
}
for(int i = 0; i < N; i++)
{
if(S[i] < 0)count++;
}
if(count == 1)
{
printf("The network is connected.");
}
else
{
printf("There are %d components.",count);
}
return 0;
}
在之前的Find函數中我用的是循環來返回根結點,結果犯了一個錯誤。
int Find(int S[],int i)
{
for(;S[i] > 0; i = S[i]);
return i;
}
for循環後的那個分號我沒加,結果導致i = S[i]這條語句在for循環判斷後(不滿足S[i] > 0),仍然被執行。