您的位置:首页 > 编程语言 > C语言/C++

拓扑排序算法

2016-07-27 13:53 447 查看
好久没写过博客了,最近看了一些关于Android的视频,可能近期会写一些关于Android的文章。

因为有一些事情吧,所以需要学习和整理一些关于排序的算法,所以给大家分享一个拓扑排序算法:

#include <iostream>
#include <cstring>
using namespace std;

const int MAXN = 100 ;

int list[MAXN][MAXN]; // 邻接表
int next[MAXN];
int vInDegree[MAXN]; // 定点入度
int tpV[MAXN]; // 拓扑序列
int n; // 定点数

int TopoSort()
{
// 不能求最大并行组
// 使用静态链栈
int i, t;
int cnt = 0 ;
int top = - 1 ;
for (i = 0 ; i < n; i ++ )
{
if (vInDegree[i] == 0 ) //将权值入栈底层为-1
{
vInDegree[i] = top;
top = i;
}
}
while (top >= 0 )
{
t = top;
top = vInDegree[top]; // 出栈
tpV[cnt ++ ] = t;
for (i = 0 ; i < next[t]; i ++ )
{
vInDegree[list[t][i]] -- ;
if (vInDegree[list[t][i]] == 0 ) // 进栈
{
vInDegree[list[t][i]] = top;
top = list[t][i];
}
}
}
return cnt;
}

int main()
{
int i, j, b;
//freopen( " test.txt " , " r " , stdin);
//函数,以指定模式重新指定到另一个文件。模式用于指定新文件的访问方式。
//freopen( const char *filename, const char *mode, FILE *stream );
//filename:需要重定向到的文件名或文件路径。
//mode:代表文件访问权限的字符串。例如,"r"表示“只读访问”、"w"表示“只写访问”、"a"表示“追加写入”。
//stream:需要被重定向的文件流。
//返回值:如果成功,则返回该指向该输出流的文件指针,否则返回为NULL。
cin>>n;//有N个节点
memset(vInDegree, 0 , sizeof (vInDegree));
//函数,将vInDegree内存块清零
for (i = 0 ; i < n; i ++ )
{
cout<<"shu ru b\ next[b]:";
cin>>b;//输入节点
cin>>next[b];//输入节点b的链长
for (j = 0 ; j < next[b]; j ++ )
{
cout<<"shu ru list[b][j]:";
cin>>list[b][j];//以节点B为头,创建链栈,并对链栈中个节点赋值
vInDegree[list[b][j]] ++ ;//到达某个节点的权值加1;
cout<<"vInDegree[list[b][j]] = "<<vInDegree[list[b][j]]<<endl;
}
}
if (TopoSort() == n)
{
for (i = 0 ; i < n; i ++ )
cout<<tpV[i]<<endl;
}
else
{
cout<<"can't not be Sort!"<<endl;
}
return 0 ;
}
这只是排序算法的一种,也希望大家有更好的算法推荐给我。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ 算法 排序算法