7-12 文件传输 (25分)
一开始用dfs来判断两点是否连通,就得了16分,剩下的样例都超时。后来改成并查集做的,第一次写的时候卡在了路径压缩,后来又多写了一点没多大用处的代码超时了…
ac的代码:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <map>
#include <queue>
#include <cmath>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#define ll long long
using namespace std;
const int maxn = 1e5+50;
int f[maxn];
void init()
{
for(int i=1; i<=maxn; i++)
{
f[i] = i;
}
}
int Find(int x)
{
if(x!=f[x])
f[x] = Find(f[x]);
return f[x];
//路径压缩另一种方法
/* int r=x;
while(f[r]!=r)
r=f[r];
int i=x,j;
while(i!=r)
{
j=f[i];
f[i]=r;
i=j;
}
return r;
*/
}
void Union(int a,int b)
{
int x = Find(a);
int y = Find(b);
if(x!=y)
f[x] = f[y];
}
int main()
{
ios::sync_with_stdio(false);
int n,a,b;
char t;
init();
cin>>n;
while(true)
{
cin>>t;
if(t=='S')
break;
else if(t=='I')
{
cin>>a>>b;
Union(a,b);
}
else if(t=='C')
{
cin>>a>>b;
if(Find(a)==Find(b))
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
}
int cnt=0;
for(int i=1; i<=n; i++)
{
if(f[i]==i)
{
cnt++;
}
}
if(cnt==1)
cout<<"The network is connected."<<endl;
else
cout<<"There are "<<cnt<<" components."<<endl;
return 0;
}
并查集超时的代码
后来想了想,即使两节点具有相同的祖先,但是其f[i]不一定是其祖先的值,还可能是其父节点的值.所以条件f[a] == f[b]是错的
例如有4组数据: 每组先输入k(代表输入k个数),每组代表一个小圈子每组都与第一个节点相连.
3 10 1 2
2 3 4
4 1 5 7 8
2 4 10
执行完并查集代码之后,每个节点的情况是:(子节点: 父节点)
1: 10
2: 10
3: 3
4: 3
5: 10
6: 6
7: 10
8: 10
9: 9
10: 3
由此可以看出,1的父节点是10,10的父节点是3,所以并不是所有子节点都和祖宗节点相连.
while(true)
{
cin>>t;
if(t=='S')
break;
else if(t=='I')
{
cin>>a>>b;
Union(a,b);
for(int i=1; i<=n; i++)
f[i] = Find(i);//这里一开始我是想让所有的点都与根节点相连,
//其实这一步就是多余的,多花了很多时间,当每次查询时直接Find ,看一看根节点相不相等就可以.
}
else if(t=='C')
{
cin>>a>>b;
// if(Find(a)==Find(b))
if(f[a]==f[b])
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
}