標籤:uva
Network Connections Time Limit: 3000ms Memory Limit: 131072KB
[PDF Link]
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 ?
Input and Output The first line of the input contains the number of dataset, and it‘s followed by a blank line. Each dataset is defined as follows:
-
1.
-
The number of computers in the network (a strictly positive integer);
-
2.
-
A list of pairs of the form:
-
(a)
-
c computeri computerj, where computeri and computerj are integers from 1 to . A pair of this form shows that computeri and computerj get interconnected.
-
(b)
-
q computeri computerj, where computeri and computerj are integers from 1 to . A pair of this form stands for the question: is computeri interconnectedwith computerj?
There‘s a blank line between datasets.
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. Print a blank line between datasets.
Sample Input
110c 1 5c 2 7q 7 1c 3 9q 9 6c 2 5q 7 5
Sample Input
1,2
題目大意:
每次q後計算失敗和成功的次數,最後輸出成功的和失敗的次數。
解題思路:
並查集,死了很多次在輸入上面,輸入還是需要一些技巧的。
代碼:
#include<iostream>#include<cstdio>#include<string>using namespace std;const int maxn=1000000;//之前一直WA忘記了str0也可能隨數位增大而增長,int t,n,parent[maxn],success,fail;char str0[100];void initial(){ for(int i=0;i<=n;i++){parent[i]=i;} success=fail=0;}void outPut(){ printf("%d,%d\n",success,fail); if(t) printf("\n");}int getRoot(int k){ if(k!=parent[k]) parent[k]=getRoot(parent[k]); return parent[k];}void Union(int a,int b){ parent[a]=b;}void solve(){ int p,q,a,b; sscanf(str0+1,"%d%d",&a,&b);//從字串裡面截取數位函數,以空格分數字. p=getRoot(a); q=getRoot(b); if(str0[0]=='c'){if(p!=q) Union(p,q);} if(str0[0]=='q'){ if(p==q) success++; else fail++; }}int main(){ scanf("%d",&t); while(t--){ cin>>n; getchar(); initial(); while(gets(str0)){ if(!str0[0]) break;//判斷是否為空白行 solve(); } outPut(); } return 0;}
Network Connections UVA 793(並查集)