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?
For example:
2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.
2, [[1,0],[0,1]]
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.
Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
在无环有向图DAG中,
由AOV网构造拓扑序列的拓扑排序算法主要是循环执行以下两步,直到不存在入度为0的顶点为止。
(1) 选择一个入度为0的顶点并输出之;
(2) 从网中删除此顶点及所有出边。
循环结束后,若输出的顶点数小于网中的顶点数,则输出“有回路”信息,否则输出的顶点序列就是一种拓扑序列
拓扑排序的序列不唯一
拓扑排序常用来确定一个依赖关系集中,事物发生的顺序。例如,在日常工作中,可能会将项目拆分成A、B、C、D四个子部分来完成,但A依赖于B和D,C依赖于D。为了计算这个项目进行的顺序,可对这个关系集进行拓扑排序,得出一个线性的序列,则排在前面的任务就是需要先完成的任务。
拓扑排序的代码:
int DAG[7][7] =
{
{INT_MAX, 1, 1, INT_MAX, INT_MAX, INT_MAX, INT_MAX},
{INT_MAX, INT_MAX, INT_MAX, 1, 1,INT_MAX, INT_MAX},
{INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX,1,1},
{INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX},
{INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX},
{INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX},
{INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX}
};
int indegree[7]={0,1,1,1,1,1,1};
/*
该图为这样一个二叉树
0
1 2
3 4 5 6
*/
void topo()
{
deque<int> q;
//寻找入度为0的点
for(int i=0; i<7; i++)
{
if(indegree[i]==0){
q.push_back(i);
}
}
int temp;
while(!q.empty()) {
temp=q.front();
q.pop_front();
cout<<temp<<" ";
for(int i=0;i<7;i++) {
if(DAG[temp][i]==1){
indegree[i]--;
if(indegree[i]==0) q.push_back(i);
}
}
}
}
将邻接矩阵改成map的形式, 相当于将邻接矩阵压缩, 应为测试用例里面有2000 × 2000的情况, 申请这么大的数组会导致Memory Limit Error(*^__^*) 嘻嘻……
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
unordered_map<int,vector<int>> DAG;
vector<int> indegree(numCourses,0); //统计每个点的入度
vector<int> output; //输出点集合
int first,second;
for(int i=0;i<prerequisites.size();i++) {
first = prerequisites[i].first;
second = prerequisites[i].second; // SECOND - > FIRST
vector<int> v=DAG[second];
if(find(v.begin(),v.end(),first)==v.end()){
DAG[second].push_back(first);
indegree[first]++;
}
}
deque<int> q; //类似与广度优先
for(int i=0;i<numCourses;i++) {
if(indegree[i]==0) {
q.push_back(i);
}
}
int temp;
while(!q.empty()) {
temp = q.front();
q.pop_front();
output.push_back(temp);
for(int j=0;j<DAG[temp].size();j++) {
int sos = DAG[temp][j];
indegree[sos]--;
if(indegree[sos]==0) q.push_back(sos);
}
}
return output.size()==numCourses;
}