1. 程式人生 > 實用技巧 >Memory Limit Exceeded

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