您的位置:首页 > 其它

uva10304 Ordering-Tasks 拓扑排序

2016-08-05 00:50 141 查看
拓扑排序的邻接表和矩阵实现

利用二维数组稀疏表很浪费空间,利用邻接表更好。

利用邻接表要堤防重复值。

例如: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
= -1;
int l = G
.size();
for(int i = 0; i < l; ++i)
{
t = G
[i];
if(visited[t] == -1)
return false;
else if(!visited[t] && !dfs(t))
return false;
}
visited
= 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  uva10304 拓扑排序