kahn算法优先队列模板
从入度考虑
int indegree[MAXN];
int topo[MAXN];
int graph[MAXN][MAXN]; //邻接矩阵
int index, n;
struct cmp1 {
bool operator ()(int &a, int &b) {
return a>b;//最小值优先
}
};
void toposort()
{
priority_queue<int,vector<int>,cmp1>q;
for (int i = 1; i <= n; i++)
{
if (!indegree[i])q.push(i);
}
index = 0;
while (!q.empty())
{
int temp= q.top();
q.pop();
topo[index++] = temp;
for (int i = 1; i <= n; i++)
{
if (graph[temp][i])
{
indegree[i]--;
if (!indegree[i])q.push(i);
}
}
}
}
DFS 实现
从出度为0考虑
bool dfs(int u)
{
vis[u] = -1;//-1用来表示顶点u正在访问
for (int i = 0; i < graph[u].size(); i++)
{
if (vis[graph[u][i]] == -1)//表示这个点进入了两次,肯定出现了环
return false;
else if (vis[graph[u][i]] == 0)
{
if (!dfs(graph[u][i]))return false;
}
}
vis[u] = 1;
topo[cnt++] = u;//放到结果数组里,输出的时候记得倒序输出,(回溯的原因)
return true;
}
bool toposort(int n)
{
memset(vis, 0, sizeof(vis));
for (int i = 1; i <= n; i++)
{
if (!vis[i])
{
if (!dfs(i)) return false;//huan
}
}
return true;
}