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.
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;
}