sunshine0 @ 2017-02-08 19:36:44
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
int pre[10001];
void mix(int,int);
int find(int);
int main()
{
int n,m,z[10001],x[10001],y[10001];
cin>>n>>m;
for(int i=1;i<=n;i++)
pre[i]=i;
for(int i=1;i<=m;i++)
{
cin>>z[i]>>x[i]>>y[i];
}
for(int i=1;i<=m;i++)
{
if(z[i]==1)
mix(x[i],y[i]);
if(z[i]==2)
{
if(find(x[i])==find(y[i]))
cout<<"Y"<<endl;
else cout<<"N"<<endl;
}
}
}
void mix(int a,int b)
{
int fa=pre[a];
int fb=pre[b];
if(fa!=fb)
pre[fa]=fb;
}
int find(int t)
{
int r=t;
while(pre[r]!=r)
r=pre[r];
int i=t,j;
while(pre[t]!=r)
{
j=pre[i];
pre[i]=r;
i=j;
}
return r;
}
by Sweetlemon @ 2017-02-08 20:23:36
不用全部读入了再遍历吧(x,y,z),可以读入一条输出一条结果
by Lyrics @ 2017-07-23 15:10:05
应该是路径压缩的问题。
路径压缩
void mix(int a,int b)
{
int fa=pre[a];
int fb=pre[b];
if(fa!=fb){
pre[fa]=fb;
pre[a]=fb;
}
}