为什么 MLE

P3367 【模板】并查集

Wenchih @ 2018-10-27 11:11:10

include <iostream>

include <cstdio>

include <algorithm>

using namespace std;

int N,M;

int ys[10001]; int zi,xi,yi;

void gb(int xx,int yy) { if(ys[xx] == ys[yy]) { return; } for (int i = ys[yy];;i = ys[i]) { if(i == ys[i]) { ys[i] = ys[xx]; break; } ys[i] = ys[xx]; } }

int find(int xx) { if(xx == ys[xx]) { return xx; } else { ys[xx] = find(ys[xx]); return ys[xx]; } }

int main() { cin.sync_with_stdio(false); cout.tie(0); freopen("test.in","r",stdin);

cin >> N >> M;
for (int i = 1;i <= N; i ++)
{
    ys[i] = i;
}

for (int i = 1;i <= M; i++)
{
    cin >> zi;
    cin >> xi >> yi;
    if(zi == 1)
    {
        gb(xi,yi);
    }
    else if(zi == 2)
    {
        if(find(xi) == find(yi))
        {
            cout << 'Y' << '\n';
        }
        else cout << 'N' << '\n';

    }
}

return 0;

}


by zhangyuxing @ 2018-10-27 11:14:52

希望更丰富的展现?使用Markdown


by zhangyuxing @ 2018-10-27 11:15:23

MLE应该是函数爆栈?


by tktk3927 @ 2018-10-27 11:28:25

freopen("test.in","r",stdin); 把这行删掉


by tktk3927 @ 2018-10-27 11:28:46

测试的时候不要开文件读入输出


by Wenchih @ 2018-10-27 11:51:14

@liuzhiyuan1234 我每次都注释掉


by Wenchih @ 2018-10-27 11:55:28

@zhangyuxing find()函数应该爆不了栈吧。


by Wenchih @ 2018-10-30 21:36:42

#include<bits/stdc++.h>

using namespace std;

int N,M;

int ys[100001];
int zi,xi,yi;

void gb(int xx,int yy)//合并
{
    if(ys[xx] == ys[yy])
    {
        return;
    }
    for (int i = ys[yy];;i = ys[i])
    {
        if(i == ys[i])
        {
            ys[i] = ys[xx];
            break;
        }
        ys[i] = ys[xx];
    }
}

int find(int xx)
{
    if(xx == ys[xx])
    {
        return xx;
    }
    else 
    {
        return ys[xx] = find(ys[xx]);
    }
}

int main()
{
    cin.sync_with_stdio(false);
    cout.tie(0);
    freopen("test.in","r",stdin);

    cin >> N >> M;
    for (int i = 1;i <= N; i ++)
    {
        ys[i] = i;
    }

    for (int i = 1;i <= M; i++)
    {
        cin >> zi;
        cin >> xi >> yi;
        if(zi == 1)
        {
            gb(xi,yi);
        }
        else if(zi == 2)
        {
            if(find(xi) == find(yi))
            {
                cout << 'Y' << '\n';
            }
            else cout << 'N' << '\n';

        }
    }

    return 0;
}

|