为什么用优化写法只过了三个点啊??大佬,球球,看看
查看原帖
为什么用优化写法只过了三个点啊??大佬,球球,看看
389268
LeM0NAdE楼主2021/8/1 12:06
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define M 1000000
void init(int *rank,int *root,int n)
{
    int i;
    for(i=0;i<n;i++)
    {
        rank[i]=0;
        root[i]=i;
    }
}
int find(int x,int *root)
{
    if(x==root[x])
    {
        return x;
    }
    return root[x]=find(root[x],root);
}
void unionn(int x,int y,int *rank,int *root)
{
    int x_root=find(x,root);
    int y_root=find(y,root);
    if(x_root!=y_root)
    {
        if(rank[x]==rank[y])
        {
            root[y]=x;
            rank[y]++;
        }
        else if(rank[x]<rank[y])
        {
            root[x]=y;
        }
        else{
            root[y]=x;
        }
    }
}

int main()
{
    int n,m,i,j,k;
    int rank[M]={0},root[M]={0};
    scanf("%d%d",&n,&m);
    init(rank,root,n);
    int x,y,op,times=0;
    while(m--)
    {
        scanf("%d%d%d",&op,&x,&y);
        if(op==1)
        {
            unionn(x,y,rank,root);
        }
        if(op==2)
        {
            i=find(x,root);
            j=find(y,root);
            if(i==j){
                printf("Y\n");
            }
            else{
                printf("N\n");
            }
        }
    }
    return 0;
}
2021/8/1 12:06
加载中...