拓扑排序的邻接表和矩阵实现
利用二维数组稀疏表很浪费空间,利用邻接表更好。
利用邻接表要堤防重复值。
例如:1,3 1,3 二维数组把一个结点赋1,但是邻接表在一个节点下会出现两个值。
设置visited数组之后一般不用担心邻接表重复值影响结果。
题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=19451
//二维数组实现
#include<cstdio>
#include<iostream>
#include<sstream>
#include<cstdlib>
#include<cmath>
#include<cctype>
#include<string>
#include<cstring>
#include<algorithm>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<ctime>
#include<vector>
#include<fstream>
using namespace std;
int G[101][101];
stack<int>topo;
int visited[105];
int n,m;
bool dfs(int v)
{
visited[v] = -1;
for(int i = 1; i <= n; ++i)
{
if(G[v][i])
{
if(visited[i] < 0)
return false;
else if(!visited[i] && !dfs(i))
return false;
}
}
visited[v] = 1;
topo.push(v);
return true;
}
bool topoSort()
{
for(int i = 1; i <= n; ++i)
{
if(!visited[i])
if(!dfs(i))
return false;
}
return true;
}
int main()
{
//freopen("F:\\data.txt","r",stdin);
int a,b;
while(scanf("%d%d",&n,&m) != EOF)
{
if(n == 0 && m == 0)
break;
memset(G,0,sizeof(G));
memset(visited,0,sizeof(visited));
for(int i = 0; i < m; ++i)
{
scanf("%d%d",&a,&b);
G[a][b] = 1;
}
topoSort();//利用返回值可以检测是否有回路
printf("%d",topo.top());//利用栈来输出
topo.pop();
for(int i = 1; i < n; ++i)
{
printf(" %d",topo.top());
topo.pop();
}
printf("\n");
}
return 0;
}
//vector<vector<int> >G实现;
#include<cstdio>
#include<iostream>
#include<sstream>
#include<cstdlib>
#include<cmath>
#include<cctype>
#include<string>
#include<cstring>
#include<algorithm>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<ctime>
#include<vector>
#include<fstream>
using namespace std;
vector<vector<int> >G;
stack<int>topo;
int visited[105];
bool dfs(int n)
{
int t;
visited[n] = -1;
int l = G[n].size();
for(int i = 0; i < l; ++i)
{
t = G[n][i];
if(visited[t] == -1)
return false;
else if(!visited[t] && !dfs(t))
return false;
}
visited[n] = 1;
topo.push(n);
return true;
}
bool topoSort(int n)
{
for(int i = 1; i <= n; ++i)
{
if(!visited[i])
if(!dfs(i))
return false;
}
return true;
}
int main()
{
//freopen("F:\\data.txt","r",stdin);
int n,m;
int a,b;
while(scanf("%d%d",&n,&m) != EOF)
{
if(n == 0 && m == 0)
break;
G.resize(n+5);
G.clear();
memset(visited,0,sizeof(visited));
for(int i = 0; i < m; ++i)
{
scanf("%d%d",&a,&b);
G[a].push_back(b);
}
topoSort(n);//可以通过返回值判断是否有回路
printf("%d",topo.top());
topo.pop();
for(int i = 1; i < n; ++i)
{
printf(" %d",topo.top());
topo.pop();
}
printf("\n");
}
return 0;
}