当两台计算机双向连通的时候,文件是可以在两台机器间传输的。给定一套计算机网络,请你判断任意两台指定的计算机之间能否传输文件?
输入格式:
首先在第一行给出网络中计算机的总数 N (2≤N≤104),于是我们假设这些计算机从 1 到 N 编号。随后每行输入按以下格式给出:
I c1 c2
其中I
表示在计算机c1
和c2
之间加入连线,使它们连通;或者是
C c1 c2
其中C
表示查询计算机c1
和c2
之间能否传输文件;又或者是
S
这里S
表示输入终止。
输出格式:
对每个C
开头的查询,如果c1
和c2
之间可以传输文件,就在一行中输出"yes",否则输出"no"。当读到终止符时,在一行中输出"The network is connected."如果网络中所有计算机之间都能传输文件;或者输出"There are k
components.",其中k
是网络中连通集的个数。
输入样例 1:
5
C 3 2
I 3 2
C 1 5
I 4 5
I 2 4
C 3 5
S
输出样例 1:
no
no
yes
There are 2 components.
输入样例 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
输出样例 2:
no
no
yes
yes
The network is connected.
解题思路
并查集。看是不是一个集合就好了。最后算联通块个数的时候,把f(i)存入set里面,set的size()就是联通块个数了。
代码如下
#include <iostream>
#include <vector>
#include <set>
#define maxn 100005
using namespace std;
int parent[maxn];
int f(int p)
{
if(p == parent[p])
return p;
else
return parent[p] = f(parent[p]);
}
set<int> s;
int main()
{
int n;
cin >> n;
for(int i = 1; i <= n; i ++)
parent[i] = i;
string ins;
while(cin >> ins){
if(ins == "S"){
for(int i = 1; i <= n; i ++)
s.insert(f(i));
if(s.size() == 1)
cout << "The network is connected." << endl;
else
cout << "There are " << s.size() << " components." << endl;
break;
}
int x, y;
cin >> x >> y;
int l = f(x);
int r = f(y);
if(ins == "I"){
if(l != r)
parent[l] = r;
}
else {
if(l == r)
cout << "yes" << endl;
else
cout << "no" << endl;
}
}
return 0;
}