20分MLE求助

P3367 【模板】并查集

tx774 @ 2022-11-17 22:45:01

#include <cstdio>
using namespace std;
const int N = 10000 + 5;
int prt[N];

int find_root(int x)
{
    if (prt[x] == x) return x;
    int f = find_root(prt[x]);
    prt[x] = f; 
    return f;
}

int main()
{
    int n;
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
        prt[i] = i;

    int m;
    scanf("%d", &m);
    while (m--)
    {
        int opt, x, y;
        scanf("%d%d%d", &opt, &x, &y);
        if (opt == 1)
        {
            int f_x = find_root(x), f_y = find_root(y);
            prt[x] = y;
        }
        if (opt == 2)
        {
            int f_x = find_root(x), f_y = find_root(y);
            if (f_x == f_y) printf("Y\n");
            else printf("N\n");
        }
    }
    return 0;
}

by tx774 @ 2022-11-17 22:46:06

还有一个WA


by Southern_Dynasty @ 2022-11-17 22:51:22

第 30 行

prt[x] = y;

改为

prt[f_x] = f_y;


by Southern_Dynasty @ 2022-11-17 22:52:04

@tx774


by tx774 @ 2022-11-17 22:52:33

@SYZ_Konnyaku 谢了


|