LintCode-615: Course Schedule and Course Schedule II 拓扑排序经典题

拓扑排序 ---排课表----数据结构 数据结构中的拓扑排序,实现课表的排序...C++编写~非本人编写..如原作者看到此程序..可与本人联系~~ 立即下载
  1. Course Schedule

There are a total of n courses you have to take, labeled from 0 to n - 1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

Example
Example 1:

Input: n = 2, prerequisites = [[1,0]]
Output: true
Example 2:

Input: n = 2, prerequisites = [[1,0],[0,1]]
Output: false

这题是一道拓扑排序的经典题。我用的是BFS。
思路跟前面贴的拓扑排序一样,最后当result.size()不等于numCourses时就返回false(也就是有环),否则返回true。
代码如下:

class Solution {
public:
    /*
     * @param numCourses: a total of n courses
     * @param prerequisites: a list of prerequisite pairs
     * @return: true if can finish all courses or false
     */
     
    struct ClassNode {
        int indegree;
        vector<int> neighbors;
        ClassNode(int x=0) : indegree(x) {}
    };
    
    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
        vector<ClassNode> courses(numCourses);
        vector<int> result;
        queue<int> q;
        for (int i=0; i<prerequisites.size(); ++i) {
            courses[prerequisites[i].first].indegree++;
            courses[prerequisites[i].second].neighbors.push_back(prerequisites[i].first);
        }
    
        for (int i=0; i<numCourses; ++i) {
            if (courses[i].indegree==0) {
                q.push(i);
                result.push_back(i);
            }
        }
        while(!q.empty()) {
            int c=q.front();
            q.pop();
            for (auto j : courses[c].neighbors) {
                courses[j].indegree--;
                if (courses[j].indegree==0) {
                    q.push(j);
                    result.push_back(j);
                }
            }
        }
        if (result.size()==numCourses) return true;
        else return false;
    }
};

[LintCode] 616 Course Schedule II
Description
There are a total of n courses you have to take, labeled from 0 to n - 1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

Example
Given n = 2, prerequisites = [[1,0]]
Return [0,1]

Given n = 4, prerequisites = [1,0],[2,0],[3,1],[3,2]]
Return [0,1,2,3] or [0,2,1,3]

Course Schedule II 要求输出符合条件的课程列表,则最后的if else 输出应改为:

        if (result.size()==numCourses) 
            return result;
        else {
            vector<int> temp;
            return  temp;
       }

即result.size()不为n时即不存在解。

二刷:

class Solution {
public:
    /*
     * @param numCourses: a total of n courses
     * @param prerequisites: a list of prerequisite pairs
     * @return: the course order
     */
    vector<int> findOrder(int numCourses, vector<pair<int, int>> &prerequisites) {
        int n = prerequisites.size();
        vector<int> result;
        
        if (n == 0) {
            for (int i = 0; i < numCourses; ++i) result.push_back(i);
            return result;
        }
        
        vector<int> degrees(numCourses); //this course depends on how many courses
        map<int, multiset<int>> edges; //course, dependencies on this course

        for (int i = 0; i < n; ++i) {
            degrees[prerequisites[i].first]++;
            edges[prerequisites[i].second].insert(prerequisites[i].first);
        }
        
        queue<int> q;
        for (int i = 0; i < numCourses; ++i) {
            if (degrees[i] == 0) q.push(i);
        }
        
        if (q.empty()) return {};
        
        while(!q.empty()) {
            int curCourse = q.front();
            q.pop();
            result.push_back(curCourse);
            
            for (auto dep : edges[curCourse]) {
                degrees[dep]--;
                if (degrees[dep] == 0) {
                    q.push(dep);
                }
            }
        }
        
        if (result.size() == numCourses) return result;
        return {};
        
    }
};

代码同步在:
https://github.com/luqian2017/Algorithm

三刷:注意visited数组没用。不需要。

class Solution {
public:
    /**
     * @param numCourses: a total of n courses
     * @param prerequisites: a list of prerequisite pairs
     * @return: the course order
     */
    vector<int> findOrder(int numCourses, vector<vector<int>> &prerequisites) {
        int rowSize = prerequisites.size();
       
        vector<int> res;
        queue<int> q;
        vector<vector<int>> followers(numCourses, vector<int>());
        vector<int> followings(numCourses, 0);
//        vector<bool> visited(numCourses, false);

        for (int i = 0; i < rowSize; i++) {
            int first = prerequisites[i][1];
            int second = prerequisites[i][0];
            followers[first].push_back(second);
            followings[second]++;
        }

        for (int i = 0; i < numCourses; i++) {
            if (followings[i] == 0) {
                q.push(i);
     //           visited[i] = false;
            }
        }

        while (!q.empty()) {
            int frontCourse = q.front();
            q.pop();
            res.push_back(frontCourse);
            for (auto followCourse : followers[frontCourse]) {
  //              if (visited[followCourse]) continue;
                followings[followCourse]--;
                if (followings[followCourse] == 0) {
                    q.push(followCourse);
                }
            }
        }

        return res;
    }
};

四刷:

class Solution {
public:
    /**
     * @param numCourses: a total of n courses
     * @param prerequisites: a list of prerequisite pairs
     * @return: the course order
     */
    vector<int> findOrder(int numCourses, vector<vector<int>> &prerequisites) {
        int n = prerequisites.size();
        //if (n == 0) return {};
        vector<int> res;
        vector<set<int>> edges(numCourses, set<int>()); //不是n
        vector<set<int>> depends(numCourses, set<int>()); //不是n
        for (int i = 0; i < n; i++) { //不是i<n
            edges[prerequisites[i][1]].insert(prerequisites[i][0]);
            depends[prerequisites[i][0]].insert(prerequisites[i][1]);
        }
        queue<int> q;
        for (int i = 0; i < numCourses; i++) {
            if (depends[i].size() == 0) {
                q.push(i);
            }
        }
        while (!q.empty()) {
            int frontNode = q.front();
            q.pop();
            res.push_back(frontNode);
            if (!edges[frontNode].empty()) {
                for (auto edge : edges[frontNode]) {
                    depends[edge].erase(frontNode);
                    if (depends[edge].size() == 0) {
                        q.push(edge);
                    }
                }
            }
        }
        if (res.size() < numCourses) return {};
        return res;
    }
};

病理WSI配准库valis教程 阅读详情

相关推荐

具身智能数据采集的工程化指南:从时间同步到质量校验

具身智能的模型训练离不开高质量的多模态轨迹数据,而数据采集并非简单的传感器记录。真实场景中,相机图像、机械臂关节状态与力觉信息必须在时间轴上精确对齐,标定的漂移和格式混乱会让看似正常的数据无法用于训练。时间同步与标定一致性,是决定数据质量的核心技术环节。在机器人抓取、操作等工程应用中,一套包含多传感器同步、轻量记录脚本、自动化质量校验与版本管理的数据采集流程,能大幅降低数据生产的失败率。本文从工程视角拆解具身数据采集中的典型问题,并给出可落地的流程设计与校验方法,帮助团队构建可持续迭代的高质量数据集。

weixin_30603633的博客 510

615. Course Schedule-课程表(拓扑排序)

Description现在你总共有 n 门课需要选,记为 0 到 n - 1.一些课程在修之前需要先修另外的一些课程,比如要学习课程 0 你需要先学习课程 1 ,表示为[0,1]给定n门课以及他们的先决条件,判断是否可能完成所有课程?样例给定 n = 2,先决条件为 [[1,0]] 返回 true给定 n = 2,先决条件为 [[1,0],[0,1]] 返回 falseSolution算法思路:已...

lighthear的博客 1518

UOS忘记密码别慌!用LiveCD工具5分钟搞定,附命令行救援模式详细步骤

本文详细介绍了UOS系统密码遗忘时的两种解决方案:图形化LiveCD工具和命令行救援模式。针对普通用户,LiveCD工具提供5分钟快速重置密码的便捷操作;而技术人员可通过命令行深度解析系统分区挂载与密码修改流程。文章还包含安全加固建议,帮助用户预防类似问题发生。

weixin_27032989的博客 589

lintcode(615)Course Schedule

Description: There are a total of n courses you have to take, labeled from 0 to n - 1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, whic

sunday0904的博客 1140

HyperMesh实战:5种复杂载荷场景下的field映射技巧(附TCL脚本)

本文详细介绍了HyperMesh在5种复杂载荷场景下的field映射技巧,包括轴承载荷的圆柱坐标系映射、粉末压力中的切向力处理、实验数据到有限元模型的场映射、多工况载荷的组合映射以及局部细化网格的边界条件传递。通过实战案例和TCL脚本,帮助工程师高效解决有限元分析中的载荷映射难题,提升工作效率。

fanta的博客 294

ECC密码的加密和解密(附带代码实现)

ECC,全称Elliptic Curve Cryptography,是椭圆曲线密码学。这是一种公钥加密技术,其安全性基于椭圆曲线离散对数问题,被广泛应用于信息安全领域。ECC的主要优势在于,相较于RSA和DSA等其他传统的公钥密码体系,它能够在提供相同安全级别的情况下,使用更短的密钥,从而减少计算量和存储空间的需求。例如,一个256位的ECC密钥提供的安全性可以与3072位的RSA密钥或DSA密钥相媲美。ECC的主要应用领域包括SSL安全证书、安全电子邮件、移动设备安全、物联网设备安全等。

xixixi7777的博客 8269

LintCode 615. Course Schedule

题目 思路 拓扑排序,BFS遍历所有点。如果最后还有点没有遍历完,返回False。 代码 class Solution: """ @param: numCourses: a total of n courses @param: prerequisites: a list of prerequisite pairs @return: true if c...

SparkSnail 443

一步步教你使用 NVIDIA 推出的全新GPU加速求解器 cuOpt:解锁超高效率的求解体验

未完成

Linshaodan520的博客 868

LintCode 615 课程表 Python题解

描述 中文English There are a total of n courses you have to take, labeled from0ton - 1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is ex...

zjy997的博客 259

YOLO11改进 - 卷积Conv | DEGConv(方向引导边缘门控卷积) : 空间分块、方向先验、轻量边缘增强

本文介绍了方向引导边缘门控卷积(DEGConv),一种专为增强边缘敏感度与方向感知能力设计的轻量级模块。该方法通过 Sobel 算子生成方向嵌入,结合条纹卷积提取水平与垂直边缘特征,并利用门控机制动态抑制背景噪声,从而精准捕捉细粒度结构。我们将 DEGConv 成功集成进 YOLO11,在 Backbone 的 SPPF 后及 Neck 的 P3、P4 分支中引入该模块以优化特征提取。实验证明,集成 DEGConv 的 YOLO11 在检测任务中表现优异,有效提升了模型对复杂边缘与方向特征的建模能力。

魔改工程师的博客 676

手把手教你ensp仿真搭建校园网(含防火墙及无线网络)系列(一)校园网核心交换机配置

本系列博客将带你从零开始,使用 华为 eNSP(Enterprise Network Simulation Platform) 仿真搭建一个完整的校园网络,涵盖 核心层、汇聚层、接入层、防火墙安全策略、无线AC+AP组网 等实战场景。无论你是网络初学者还是希望深化实战经验的工程师,都能通过本教程掌握企业级网络的规划、配置与排错技巧。

echo的博客 3795

拓扑排序:课程表Course Schedule

There are a total of n courses you have to take, labeled from 0 to n - 1.Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair:

知之可否 1818

中小企业办公网络配置综合实验华为设备(NAT+策略路由+OSPF+VLAN)

组网需求: 1、PC1、2、3、4均可以访问internet的lo0:8.8.8.8 2、PC1、PC4通过电信ISP访问internet;PC2、PC3通过联通ISP访问internet; 需求分析: 1、internet路由器模拟公网,8.8.8.8模拟公网IP;电信ISP、联通ISP路由器模拟电信和联通运营商;出口路由为企业出口路由器;这四个路由器直连链路之间运行ospf,配置动态路由,实现互通; 2、出口路由与三层交换直连链路运行ospf,动态同步路由信息; 3、出口路由器内网端口配..

A soul tortured by desire 7125

课程表-LintCode

现在你总共有 n 门课需要选,记为 0 到 n - 1. 一些课程在修之前需要先修另外的一些课程,比如要学习课程 0 你需要先学习课程 1 ,表示为[0,1] 给定n门课以及他们的先决条件,判断是否可能完成所有课程?样例: 给定 n = 2,先决条件为 [[1,0]] 返回 true 给定 n = 2,先决条件为 [[1,0],[0,1]] 返回 false思路: 利用拓扑排序来判断是否存

kane的博客 454

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

拓扑排序:课程表Course Schedule2

https://leetcode.com/problems/course-schedule-ii/class Solution { public: vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) { vector<int> res; vector<int>

知之可否 914

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

lintcode615. 课程表 拓扑排序

现在你总共有 n 门课需要选,记为 0 到 n - 1. 一些课程在修之前需要先修另外的一些课程,比如要学习课程 0 你需要先学习课程 1 ,表示为[0,1] 给定n门课以及他们的先决条件,判断是否可能完成所有课程? 样例 例1: 输入: n = 2, prerequisites = [[1,0]] 输出: true 例2: 输入: n = 2, prerequisites = [[1,0]...

sinb妃的博客 222

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

Course Schedule I && II 总结

There are a total of n courses you have to take, labeled from 0 to n - 1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as

sundawei2016的博客 293

leetcode210——Course Schedule II

题目大意:给出n个课程之间的先修关系,找出一个上课的顺序 分析:拓扑排序,有环就矛盾,没有环就逐个向答案中添加入度为0的结点 代码: class Solution { public: vector&lt;int&gt; findOrder(int numCourses, vector&lt;pair&lt;int, int&gt;&gt;&amp; prerequisites) {...

tzyshiwolaogongya的博客 403

Leetcode 207 Course Schedule 课程表

你需要上n个课程,标记为0~n-1。有些课程有前导课,比如你要上课程0必须先上课程1,我们用一个整数对[0,1]来表示。给出课程的总数和一系列的课程先导关系对,判断是否可能上完所有的课程。

(ง •̀_•́)ง 6515

5.27.2022 Lintcode今日打卡 2042 查询课程表中所有的课程名和创建日期中的年份和月份

描述 题目描述:请编写 SQL 语句,查询课程表courses所有课程中的课程名(name)和创建日期中的年份(别名:year)和月份( 别名:month)。 表定义:courses(课程表) 列名 类型 注释 id int unsigned 主键 name varchar 课程名称 student_count int 学生总数 created_at datetime 课程创建时间 teacher_id int ..

esbqjl的博客 497

Course Schedule II解答

Question There are a total ofncourses you have to take, labeled from0ton-1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expr...

weixin_30363817的博客 131

Course Schedule/Course Schedule II

题目分析 1. 这两题的问题很相似,于是放在一起做。 2. 第一题可以发现是要判断有向图中是否存在有环。一开始我的思路是用BFS遍历图,然后如果一个点入队两次就说明有环,根据这个思路写了一遍运行之后很快就发现是有问题的,这种做法只可以对无向图找环,但是对于有向图来说是不成立的。一个显然的反例是  0  |   \ 1 ->2 于是我上网找了一下有向图找环的思路。 3. 一个比较通用的

mahua23的博客 406

LintCode 题目答案

LintCode 题目答案

Super_Tiger_Lee的博客 6350

Lintcode C++代码

给定一个字符串所表示的括号序列,包含以下字符: ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, 判定是否是有效的括号序列。主要用用到堆栈 操作 不熟悉的小伙伴,自己恶补! 以下是一位博主的的代码;class Solution { public: /** * @param s A string * @return whether the string

u013174482的博客 784

LeetCode207课程表

题目:现在你总共有 n 门课需要选,记为 0 到 n - 1。一些课程在修之前需要先修另外的一些课程,比如要学习课程 0 你需要先学习课程 1 ,表示为: [0,1]给定 n 门课以及他们的先决条件,判断是否可能完成所有课程?例如:2, [[1,0]]总共有2门课程可供选择。选取课程 1之前,你需要完成课程 0。所以这是可能的。2, [[1,0],[0,1]]总共有 2 门课程可供选择。要参加课程...

qq_38595487的博客 2029

615 - Course Schedule

2017.9.11 刚开始想的是,建立parent 和 children的树,如果有既是children 又是parent的节点,那么就返回false。 这种方法没有超时,但是超出了空间限制。 后来学习到采用拓扑排序的办法。关于图的思路写在了代码的注释里边。 在细节的处理方面有不同的方法。一个是最后的最后统一判断是不是还有入度不为0的点。这样会超时。 后来是在找入度为0的点的时候

Missbubu的博客 325
上一篇: BFS宽搜和DFS深搜小结
下一篇: LintCode-611: Knight Shortest Path (BFS经典题)
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值