复习了vector<pair<int, int>>使用方法
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 1:
Input: 2, [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
Example 2:
Input: 2, [[1,0],[0,1]]
Output: false
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should
also have finished course 1. So it is impossible.
题目链接:https://leetcode.com/problems/course-schedule/
这题的加强版Leetcode 210. Course Schedule II 拓扑排序的代码和这题基本一样
class Solution {
public:
bool canFinish(int num, vector<pair<int, int>>& pre) {
int c=0;
queue<int> q;
vector<vector<int>> adjList(num);//邻接表
vector<int> inDegree(num,0);//入度表
for(auto i:pre)
{
adjList[i.second].emplace_back(i.first);
inDegree[i.first]++;
}
for(int i=0;i<num;i++)
{
if(inDegree[i]==0)
{
c++;
q.push(i);
}
}
while(!q.empty())
{
int tmp=q.front();
q.pop();
for(auto i:adjList[tmp])
{
inDegree[i]--;
if(inDegree[i]==0)
{
c++;
q.push(i);
}
}
}
if(c==num)
return true;
return false;
}
};