當前位置:編程學習大全網 - 編程語言 - 簡單拓撲排序算法C語言

簡單拓撲排序算法C語言

#include <cstdio>

#include <cstring>

#include <stack>

using namespace std;

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Description: 表示圖的結點的鄰接邊

struct Edge

{

int dest;

Edge *next;

} **graph;

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Description: 添加壹個邊

// Input: e - 要添加邊的結點, p - 目的地

// Output: e - 添加邊後的結點

void AddEdge(Edge *&e, int p)

{

if(!e)

{

e = new Edge;

e->dest = p;

e->next = 0;

}

else

{

Edge *tail = e;

while (tail->next) tail = tail->next;

tail->next = new Edge;

tail = tail->next;

tail->dest = p;

tail->next = 0;

}

}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Description: 輸入結點之間的邊

// Input: Console下用戶輸入,起點和終點; m - 邊的個數

// Output: graph - 圖;

void Input(int &m)

{

int i, a, b; // a->b存在邊(有向)

for (i = 0; i < m; i++)

{

scanf("%d %d", &a, &b);

AddEdge(graph[a], b);

}

}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Description: 獲得每個結點的入度

// Input: n - 結點的個數

// Output: degree - 每個結點的入度

void GetDegree(int *degree, int n)

{

int i = 0;

Edge *edge;

memset(degree, 0, sizeof(int) * n);

for (i = 0; i < n; i++)

{

edge = graph[i];

while(edge)

{

degree[edge->dest]++;

edge = edge->next;

}

}

}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Description: 拓撲排序

// Input: n - 結點個數

// Output: console下輸出壹個正確的拓撲序

void TopoSort(int n)

{

int *degree = new int[n]; // 初始化所有結點的入度

GetDegree(degree, n);

stack<int> s; // 獲得入度為0的結點,並入棧

int i = 0;

for (i = 0; i < n; i++)

if (degree[i] == 0)

s.push(i);

int index = 0; // 結點的下標

Edge *edge; // 當前結點鄰接表

while (!s.empty())

{

index = s.top();

printf("%d", index);

s.pop();

edge = graph[index];

while (edge)

{

if (--degree[edge->dest] == 0)

s.push(edge->dest);

edge = edge->next;

}

}

delete []degree;

}

int main()

{

int n, m; // 結點個數、邊個數

scanf("%d %d", &n, &m);

int i;

graph = new Edge*[n];

for(i = 0; i < n; i++) graph[i] = 0;

Input(m);

TopoSort(n);

return 0;

}

  • 上一篇:100分!!!IC芯片!!!
  • 下一篇:壹鍵目標宏設置教程(目標宏怎麽做的)
  • copyright 2024編程學習大全網