题目描述
Bob, who is a network administrator, supervises a network of computers. He is keeping a log connections between the computers in the network. Each connection is bi-directional. Two computers are interconnected if they are directly connected or if they are interconnected with the same computer. Occasionally, Bob has to decide, quickly, whether two given computers are connected, directly or indirectly, according to the log information.
Write a program which based on information input from a text file counts the number of successful and the number of unsuccessful answers to the questions of the kind :
is computeri
interconnected with computerj
?
输入输出格式
输入格式
The program reads data from a text file, as follows:
- The number of computers in the network (a strictly positive integer);
- A list of pairs of the form: (a)
c
computeri
computerj
, wherecomputeri
andcomputerj
are integers from1
to no of computers. A pair of this form shows thatcomputeri
andcomputerj
get interconnected.(b)q
computeri
computerj
, wherecomputeri
andcomputerj
are integers from1
to no of computers. A pair of this form stands for the question:
Each pair is on a separate line. Pairs can appear in any order, regardless of their type. The log is updated after each pair of type (a) and each pair of type (b) is processed according to the current network configuration.
For example, the input file illustrated in the sample below corresponds to a network of 10
computers and 7
pairs. There are N1
successfully answered questions and N2
unsuccessfully answered questions. The program prints these two numbers to the standard output on the same line, in the order: successful answers, unsuccessful answers, as shown in the sample output.
输出格式
The program prints two integer numbers to the standard output on the same line, in the order: ‘successful answers, unsuccessful answers’, as shown in the sample output.
输入输出样例1
输入
10
c 1 5
c 2 7
q 7 1
c 3 9
q 9 6
c 2 5
q 7 5
0
输出
1,2
解题思路:
#include <stdio.h>
#define MN 10000
int n, i;
int con, ncon;
struct vertex
{
struct vertex *father;
int size;
};
struct vertex v[MN];
char buf[100];
struct vertex *find (int i)
{
struct vertex *pv = v + i, *av, *rv;
for (av = pv; av->father; av = av->father)
continue;
rv = av;
for (av = pv; av != rv; av = pv)
{
pv = av->father;
av->father = rv;
}
return rv;
}
void join(struct vertex *v1, struct vertex *v2)
{
if (v1 == v2)
return;
if (v1->size < v2->size)
v1->father = v2;
else
v2->father = v1;
}
int main(void)
{
char c[2];
int f, t;
gets (buf);
while (1)
{
sscanf (buf, "%d", &n);
if (n == 0)
return 0;
for (i = 0; i < n; i++)
{
v[i].father = NULL;
v[i].size = 1;
}
con = ncon = 0;
while (1)
{
gets (buf);
if (*buf == 'c')
{
sscanf (buf, "%s %d %d", c, &f, &t);
join (find (f - 1), find (t - 1));
}
else if (*buf == 'q')
{
sscanf (buf, "%s %d %d", c, &f, &t);
if (find (f - 1) == find (t - 1))
con++;
else
ncon++;
}
else
{
printf ("%d,%d\n", con, ncon);
break;
}
}
}
}