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, " \n"[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, " \n"[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

 

posted @ 2020-09-19 18:26  hulian425  阅读(627)  评论(0编辑  收藏  举报