拓扑排序 基于DFS
来源:互联网 发布:jsp项目源码 编辑:程序博客网 时间:2024/05/04 10:04
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
const int Max = 1001;
int M[Max][Max], vis[Max], topo[Max], pos;
int n, m;
bool DFS(int u)
{
vis[u] = -1;
for(int v = 1; v <= n; v++)
{
if(M[u][v])
{
if(vis[v] == -1) return false;
else if(!vis[v] && !DFS(v)) return false;
}
}
vis[u] = 1;
topo[pos--] = u;
return true;
}
bool toposort()
{
pos = n;
memset(vis, 0, sizeof(vis));
for(int u = 1; u <= n; u++)
{
if(!vis[u]){
if(!DFS(u)) return false;
}
}
return true;
}
int main()
{
//freopen("in.txt", "r", stdin);
while(cin >> n >> m && n)
{
memset(M, 0, sizeof(M));
memset(vis, 0, sizeof(vis));
int x, y;
pos = n;
for(int i = 1; i <= m; i++)
{
cin >> x >> y;
M[x][y] = 1;
}
toposort();
for(int i = 1; i <= n; i++)
{
if(i != 1) cout << " ";
cout << topo[i];
}
cout << endl;
}
return 0;
#include <bits/stdc++.h>
using namespace std;
const int Max = 1001;
int M[Max][Max], vis[Max], topo[Max], pos;
int n, m;
bool DFS(int u)
{
vis[u] = -1;
for(int v = 1; v <= n; v++)
{
if(M[u][v])
{
if(vis[v] == -1) return false;
else if(!vis[v] && !DFS(v)) return false;
}
}
vis[u] = 1;
topo[pos--] = u;
return true;
}
bool toposort()
{
pos = n;
memset(vis, 0, sizeof(vis));
for(int u = 1; u <= n; u++)
{
if(!vis[u]){
if(!DFS(u)) return false;
}
}
return true;
}
int main()
{
//freopen("in.txt", "r", stdin);
while(cin >> n >> m && n)
{
memset(M, 0, sizeof(M));
memset(vis, 0, sizeof(vis));
int x, y;
pos = n;
for(int i = 1; i <= m; i++)
{
cin >> x >> y;
M[x][y] = 1;
}
toposort();
for(int i = 1; i <= n; i++)
{
if(i != 1) cout << " ";
cout << topo[i];
}
cout << endl;
}
return 0;
}
大神: http://blog.csdn.net/lisonglisonglisong/article/details/45543451
阅读全文
1 0
- 拓扑排序 基于DFS
- 基于DFS的拓扑排序
- 基于DFS的拓扑排序
- 拓扑排序(Kahn算法和基于DFS求解法)
- 拓扑排序+DFS
- poj1128 拓扑排序+DFS
- 拓扑排序-DFS
- DFS,拓扑排序
- 拓扑排序 dfs
- hdoj538Ponds【dfs+拓扑排序】
- POJ1270【拓扑排序+DFS】
- DFS拓扑排序
- 拓扑排序DFS做法
- 拓扑排序--dfs
- 拓扑排序的两种实现--基于dfs和基于入度
- poj 1094 DFS--》拓扑排序
- poj 1270(dfs+拓扑排序)
- 用dfs实现拓扑排序
- 右键发送到菜单修改
- Python的zip函数
- bootstrap-select 与 jquery validate 页面数据检验 错误
- vim函数跳转技巧
- note_cloud--注册功能
- 拓扑排序 基于DFS
- Android Studio 快捷键整理分享
- Android Studio2.2 配置NDK
- 百练_3864:与7无关的数
- android关于每次点击图标进入应用后都会重新创建启动页的问题
- Mycat水平拆分之十种分片规则
- XMLMapperBuilder源码分析
- js工具方法
- 猫奴大数据_你中枪了吗?