拓扑习题 leetcode 207 cource schedule

#include <iostream>
#include <vector>

using namespace std;

class Solution {
  public:
    struct ArchNode {
        int idx;
        struct ArchNode* next;
        ArchNode(int i): idx(i), next(nullptr) {}
    };
    struct VertexNode {
        struct ArchNode* first = nullptr;
        struct ArchNode* tail = nullptr;
    };
    bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
        const int n = numCourses;
        int in_degree[n];
        fill_n(in_degree, n, 0);
        struct VertexNode vertexes[n];
        const unsigned int arch_size = prerequisites.size(); // 必须使用unsigned; 否则leetcode santizer过不去; int有非正0;
        struct ArchNode* arches[arch_size];

        vector<int> result;

        // 构造入度数组, 邻接表;
        int arch_count = 0;
        for (auto edge : prerequisites) {
            int idx = edge[0], st = edge[1];
            in_degree[idx]++;

            ArchNode* p = new ArchNode(idx);
            arches[arch_count++] = p;  //记录堆中创建的边结点;
            if (vertexes[st].first == nullptr) {
                vertexes[st].first = p;
                vertexes[st].tail = p;
            } else {
                vertexes[st].tail->next = p;
                vertexes[st].tail = vertexes[st].tail->next;
            }
        }
        int count = numCourses;
        while (count--) {
            int i = find_indegree_0_node(in_degree, n);
            if (i == -1){
                cout << "can't find node whose in-degree is 0" << endl;
                return false;
            }   

            ArchNode* q = vertexes[i].first;
            while (q) {
                int j = q->idx;
                in_degree[j]--;
                q = q->next;
            }   
            in_degree[i] = -1; 
            result.push_back(i);
        }
        cout << "count=" << count << endl;
        cout << "topologic list=";
        for(auto r : result)
            cout << r << " ";
        cout << endl;

        clearVertexNodes(arches, arch_count);
        return true;
    }

  private:
    int find_indegree_0_node(int* in_degree, const int size) {
        for (int i = 0; i < size; ++i) {
            if (in_degree[i] == 0)
                return i;
        }
        return -1;
    }

    void clearVertexNodes(ArchNode** arches, int size) {
      for (int j = 0; j < size; ++j) {
        delete arches[j];
      }
    }
};
  • 第一次提交就通过了;
  • 删除了创建的边集节点避免内存泄漏; 但是从提交结果来看并没有省多少内存;
  • arch_count必须是unsigned, 避免负0出现在数组定义;

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值