其实我想说oj上不少题目的数据不是很完善,就拿有关连通分量的题目来说吧,oj上提交对的代码,交到pta上就有错误。仔细研究一下算法,发现当时没有理解透彻改算法,但是oj给你一个AC,自我感觉良好。真是难受的一批。
并查集就是认亲戚(是一种树形结构),将直接或间接有关系的点放到一个集合中去,这时候进行的处理都是对代表进行操作的。所谓的代表就是这个集合的根节点。
当两台计算机双向连通的时候,文件是可以在两台机器间传输的。给定一套计算机网络,请你判断任意两台指定的计算机之间能否传输文件?
题目描述:
输入格式:
首先在第一行给出网络中计算机的总数 N (2≤N≤10
4
),于是我们假设这些计算机从 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.
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
#include <stack>
#include <queue>
#include <cmath>
#define INF 0x3f3f3f3f
using namespace std;
int f[100005];
int father(int x)
{
if(x==f[x])
return x;
else return f[x] = father(f[x]);
}
int main()
{
int n;
int a,b;
string ch;
cin>>n;
for(int i=1; i<=n; i++)
f[i] = i;
while(1)
{
cin>>ch;
if(ch=="S")
break;
else if(ch=="C")
{
cin>>a>>b;
if(father(a)!=father(b))
{
printf("no\n");
}
else
{
printf("yes\n");
}
}
else if(ch=="I")
{
cin>>a>>b;
if(father(a)!=father(b))
f[father(b)] = father(a);//这里就是我想说的关键,以前是这样写的:f[b] = f[a],
//现在仔细想想根本不对。
}
}
int sum = 0;
for(int i=1;i<=n;i++)
if(f[i]==i)
sum++;
if(sum==1)
printf("The network is connected.\n");
else printf("There are %d components.\n",sum);
return 0;
}
有兴趣的可以做一下这个题,用错误的方法就能过!
当然有很多方法可以过。
http://acm.sdut.edu.cn/onlinejudge2/index.php/Home/Index/problemdetail/pid/2129.html