MLE爆栈求解释

P3367 【模板】并查集

Special_Tony @ 2023-09-24 13:43:16

MLE(应该是爆栈):

# include <bits/stdc++.h>

# define ffor(i,name) \
    for (auto i = name.begin (); i != name.end (); ++ i)

# define reg register

using namespace std;

typedef long long ll;

typedef pair <int, int> pii;

typedef pair <ll, ll> pll;

int n, m, f[10005], x, y, op;

int find (int x) {

    return x == f[x] ? x : f[x] = find (f[x]);

}

int main () {

    ios::sync_with_stdio (0);

    cin.tie (0);

    cout.tie (0);

    cin >> n >> m;

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

    while (m --) {

        cin >> op >> x >> y;

        if (op < 2)
            f[find (x)] = y; //这里不一样
        else
            cout << (find (x) == find (y) ? "Y\n" : "N\n");

    }

    return 0;

}

AC:

# include <bits/stdc++.h>

# define ffor(i,name) \
    for (auto i = name.begin (); i != name.end (); ++ i)

# define reg register

using namespace std;

typedef long long ll;

typedef pair <int, int> pii;

typedef pair <ll, ll> pll;

int n, m, f[10005], x, y, op;

int find (int x) {

    return x == f[x] ? x : f[x] = find (f[x]);

}

int main () {

    ios::sync_with_stdio (0);

    cin.tie (0);

    cout.tie (0);

    cin >> n >> m;

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

    while (m --) {

        cin >> op >> x >> y;

        if (op < 2)
            f[find (x)] = find (y); //这里不一样
        else
            cout << (find (x) == find (y) ? "Y\n" : "N\n");

    }

    return 0;

}

为啥啊


by Special_Tony @ 2023-09-24 13:43:32

@gggoodgame


by yinhee @ 2023-09-24 13:46:21

你这样写可能导致fa[x]=y,fa[y]=x就死递归了。


by Special_Tony @ 2023-09-24 13:49:32

/bx @yinhee


by DELA @ 2023-09-24 13:50:38

@sz_mane x y 在同一个集合的时候会寄。


by Special_Tony @ 2023-09-24 13:56:08

@DELA 蟹蟹


by Special_Tony @ 2023-09-24 13:57:42

@google_chrome 你@我啥了


by DELA @ 2023-09-24 13:58:40

@sz_mane

@google_chrome 你@我啥了

他说没有这种写法,建议重新学并查集


|