Memory Limit Exceeded

1. 使用bfs时候出现了这种错误

错误写法

void bfs()
{
    priority_queue<int, vector<int>, greater<int> > heap;
    heap.push(0);
    for (int i = 0; i <= n; i++) st[i] = false;
    st[0] = true;
    int cnt = 0;
    while (heap.size())
    {
        auto t = heap.top();
        // ans.push_back(t);
        cnt++;
        if (cnt >1)
        printf("%d%c", t, " 
"[cnt == n+1]);
        heap.pop();

/// 错误写法
        st[t] = true;
        for (int i = h[t]; i!= -1; i = ne[i])
        {
            int j = e[i];
            if (st[j]) continue;
            heap.push(j);

        }
    }
    return;
}
View Code

正确写法

void bfs()
{
    priority_queue<int, vector<int>, greater<int> > heap;
    heap.push(0);
    for (int i = 0; i <= n; i++) st[i] = false;
    st[0] = true;
    int cnt = 0;
    while (heap.size())
    {
        auto t = heap.top();
        // ans.push_back(t);
        cnt++;
        if (cnt >1)
        printf("%d%c", t, " 
"[cnt == n+1]);
        heap.pop();
        for (int i = h[t]; i!= -1; i = ne[i])
        {
            int j = e[i];
            if (st[j]) continue;
            heap.push(j);
            st[j] = true;
        }
    }
    return;
}
View Code
原文地址:https://www.cnblogs.com/hulian425/p/13697151.html