您的位置:首页 > Web前端

PAT : 05-树7. File Transfer (25)

2015-04-08 20:14 696 查看
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.

考察的是并查集的操作。合集内的所有节点全部都能两两相互访问,只要两个合集分别有一个节点能相互连接,则这两个集合的所有节点均可两两相互访问,即两个集合做并运算,并成一个集合。最后输出的component数是操作完成后集合的数量。合集的根节点的parent值为负,其绝对值为合集中节点的数目,以方便在集合合并时减少合集的层数。

#include <stdio.h>
#include <stdlib.h>

struct node
{
int data;
int parent;
};

void initlist (node *nodelist, int n)
{
for(int i = 1; i <= n; i++)
{
nodelist[i].data = i;
nodelist[i].parent = -1;
}
}

int findparent (node *nodelist, int num)
{
for(; nodelist[num].parent > 0; num = nodelist[num].parent);

return num;
}

int main()
{
int n;
scanf("%d", &n);
getchar();

node *nodelist = (node *) malloc ((n+1) * sizeof(node));
initlist(nodelist, n);

char ch;
int a, b;
int ap, bp;
while(scanf("%c", &ch))
{
if(ch == 'S')
break;

scanf("%d %d", &a, &b);
getchar();

ap = findparent(nodelist, a);
bp = findparent(nodelist, b);

if(ch == 'I')
{
if(ap != bp)
{
if(nodelist[ap].parent <= nodelist[bp].parent)
{
nodelist[ap].parent += nodelist[bp].parent;
nodelist[bp].parent = ap;
}
else
{
nodelist[bp].parent += nodelist[ap].parent;
nodelist[ap].parent = bp;
}
}
}

else if(ch == 'C')
{
if(ap == bp)
printf("yes\n");
else
printf("no\n");
}
}

int component = 0;
for(int i = 1; i <= n; i++)
if(nodelist[i].parent < 0)
component ++;

if(component > 1)
printf("There are %d components.\n", component);
else
printf("The network is connected.\n");

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: