lc课程表2 拓扑排序的理解和反三
const int N=4010;
class Solution {
public:
int h[N], e[N], ne[N], idx;
int q[N];
int d[N];
void add(int a, int b)
{
e[idx]=b, ne[idx]=h[a], h[a]=idx++;
}
bool topsort(int n)
{
int hh=0,tt=-1;
for (int i = 0; i < n; ++i) {
if(!d[i])
q[++tt]=i;
}
while(hh<=tt)
{
int t=q[hh++];
for(int i=h[t];i!=-1;i=ne[i])
{
int j=e[i];
if(--d[j]==0)
q[++tt]=j;
}
}
return tt==n-1;
}
vector<int> findOrder(int num, vector<vector<int>>& p) {
vector<int> ans(num);
memset(h, -1, sizeof h);
for(auto x:p)
{
add(x[1],x[0]);
d[x[0]]++;
}
if(topsort(num))
{
for (int i = 0; i < num; ++i)
ans[i]=q[i];
return ans;
}
return {};
}
};