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 kcomponents.” 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.
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
no
no
yes
yes
The network is connected.
#include
#include
#define MAXN 10001
typedef int ElementType;
typedef int SetName;
typedef ElementType SetType[MAXN];
void Union(SetType S, SetName Root1, SetName Root2)
{
if(S[Root1] < S[Root2])
{
S[Root1] += S[Root2];
S[Root2] = Root1;
}
else
{
S[Root2] += S[Root1];
S[Root1] = Root2;
}
}
SetName Find(SetType S, SetName X)
{
if(S[X] < 0)
return X;
else
return Find(S,S[X]);
}
/*
SetType CreateSet()
{
SetType s;
int i;
s = (SetType)malloc(sizeof(SetType));
for(i = 0;i
int NumofComponents(SetType s,int N)
{
int i, num = 0;
for(i = 1;i <= N;i++)
{
if(s[i] < 0)
num++;
}
return num;
}
int main()
{
SetType s;
int N,i,com_num;
char Action;
SetName a,b;
SetName root1,root2;
for(i = 0;i1 ;
}
scanf("%d",&N);
getchar();
scanf("%c",&Action);
while(Action != 'S')
{
if(Action == 'I')
{
scanf("%d %d",&a,&b);
getchar();
root1 = Find(s,a);
root2 = Find(s,b);
if(root1 != root2)
Union(s,root1,root2);
}
else
{
scanf("%d %d",&a,&b);
getchar();
root1 = Find(s,a);
root2 = Find(s,b);
if(root1 == root2)
printf("yes\n");
else
printf("no\n");
}
scanf("%c",&Action);
}
com_num = NumofComponents(s,N);
if(com_num == 1)
printf("The network is connected.\n");
else
printf("There are %d components.",com_num);
return 0;
}