各位大牛帮忙看看为什么错了。。。感激不尽!!!

P3367 【模板】并查集

xrz2895538112xrz @ 2018-02-01 21:26:46

C++代码:

···

include<iostream>

include<cstdio>

using namespace std; int N,M,f[100005]; int find(int x) { if(f[x]==x) return x; return f[x]=find(f[x]); } void merge(int a,int b) { int fa=find(a),fb=find(b); f[a]=fb; } int main() { cin>>N>>M;

for(int i=1;i<=N;i++)
    f[i]=i;

for(int i=1,z=0,x=0,y=0;i<=M;i++)
{
    cin>>z>>x>>y;
    if(z==1)
        merge(x,y);
    else
    {
        int fa=find(x),fb=find(y);
        if(fa==fb)
            cout<<"Y\n";
        else
            cout<<"N\n";
    }
}
return 0;

} ···

帮忙看看,非常感谢!!!


by xrz2895538112xrz @ 2018-02-01 21:28:13

对不起打错格式了!!!

#include<iostream>
#include<cstdio>
using namespace std;
int N,M,f[100005];
int find(int x)
{
    if(f[x]==x)
        return x;
    return f[x]=find(f[x]); 
}
void merge(int a,int b)
{
    int fa=find(a),fb=find(b);
    f[a]=fb;
}
int main()
{
    cin>>N>>M;

    for(int i=1;i<=N;i++)
        f[i]=i;

    for(int i=1,z=0,x=0,y=0;i<=M;i++)
    {
        cin>>z>>x>>y;
        if(z==1)
            merge(x,y);
        else
        {
            int fa=find(x),fb=find(y);
            if(fa==fb)
                cout<<"Y\n";
            else
                cout<<"N\n";
        }
    }
    return 0;
}

谢谢!


by Night_Aurora @ 2018-02-01 21:30:35

@xrz2895538112xrz merge里面是f[fa]=fb吧


by _LiM @ 2018-02-01 21:39:35

同意楼上
应该是拿两个元素的祖先进行合并


by Gypsophila @ 2018-02-01 21:41:11

f[fa] = fb; 是这句没错


by xrz2895538112xrz @ 2018-02-02 08:18:37

谢谢!


|