mjtlyzbsy @ 2017-03-29 17:24:59
#include<cstdio>
#include<iostream>
#include<cmath>
using namespace std;
int par[10001],rank[10001];
int init(int n){
for(int i=1;i<=n;i++){
par[i]=i;
rank[i]=0;
}
return ;
}
int find(int x){
if(par[x]==x)return x;
else return par[x]=find(par[x]);
}
bool pan(int x,int y){
x=find(x);
y=find(y);
if(x==y)return true;
return false;
}
void unite(int x,int y){
x=find(x);
y=find(y);
if(rank[x]<rank[y])par[x]=y;
else{
par[y]=x;
if(rank[x]==rank[y])rank[x]++;
}
}
int main(){
int n,m;
cin>>n>>m;
init(n);
for(int i=1;i<=m;i++){
int z,x,y;
cin>>z>>x>>y;
if(z==1)unite(x,y);
else {
if(pan(x,y))cout<<y
}
}
return 0;
}
by mjtlyzbsy @ 2017-03-29 17:26:40
sorry,贴错了
by mjtlyzbsy @ 2017-03-29 17:29:05
#include<cstdio>
#include<iostream>
#include<cmath>
using namespace std;
int par[10001],rank[10001];
void init(int n){
for(int i=1;i<=n;i++){
par[i]=i;
rank[i]=0;
}
return ;
}
int find(int x){
if(par[x]==x)return x;
else return par[x]=find(par[x]);
}
bool pan(int x,int y){
x=find(x);
y=find(y);
if(x==y)return true;
return false;
}
void unite(int x,int y){
x=find(x);
y=find(y);
if(rank[x]<rank[y])par[x]=y;
else{
par[y]=x;
if(rank[x]==rank[y])rank[x]++;
}
}
int main(){
int n,m;
cin>>n>>m;
init(n);
for(int i=1;i<=m;i++){
int z,x,y;
cin>>z>>x>>y;
if(z==1)unite(x,y);
else {
if(pan(x,y))cout<<"Y"<<endl;
else cout<<"N"<<endl;
}
}
return 0;
}
by zhengrunzhe @ 2017-03-29 17:41:24
find大写试看看
by Sonorous @ 2017-03-29 18:34:17
@一朝被蛇咬 rank在C++11好像是保留字,不能作为变量或数组出现。。
by Sonorous @ 2017-03-29 18:35:12
把rank改一下,比如rk,rak什么的
by mjtlyzbsy @ 2017-03-31 16:14:11
#include<cstdio>
#include<iostream>
#include<cmath>
using namespace std;
int par[10001],rak[10001];
void init(int n){
for(int i=1;i<=n;i++){
par[i]=i;
rak[i]=0;
}
return ;
}
int Find(int x){
if(par[x]==x)return x;
else return par[x]=Find(par[x]);
}
bool pan(int x,int y){
x=Find(x);
y=Find(y);
if(x==y)return true;
return false;
}
void unite(int x,int y){
x=Find(x);
y=Find(y);
if(rak[x]<rak[y])par[x]=y;
else{
par[y]=x;
if(rak[x]==rak[y])rak[x]++;
}
}
int main(){
int n,m;
cin>>n>>m;
init(n);
for(int i=1;i<=m;i++){
int z,x,y;
cin>>z>>x>>y;
if(z==1)unite(x,y);
else {
if(pan(x,y))cout<<"Y"<<endl;
else cout<<"N"<<endl;
}
}
return 0;
}
//谢谢dalao