拓扑排序示例程序

April 28, 2013
Graph

输入:顶点个数n,边数m,然后是m行,表示每条边的起点和终点u, v 表示从顶点u到顶点v的一条有向边。输入0 0 表示结束。 输出:如果不存在有向环,则输出一个拓扑有序序列;否则,输出“Netword has a cycle!”  


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <cmath>
#include <algorithm>
#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1
using namespace std;
typedef long long int LL;
const int MAXN =  0x3f3f3f3f;
const int  MIN =  -0x3f3f3f3f;
const double eps = 1e-9;
const int dir[8][2] = {{0,1},{1,0},{0,-1},{-1,0},{-1,1},
  {1,1},{1,-1},{-1,-1}};
int n, m, Count[100], i, j, top, out[100];
struct ArcNode{
  int to; struct ArcNode *next;
};
ArcNode *List[100];
void topsort()
{
  ArcNode *temp; top = -1; int k, len = 0; bool flag = true;
  for (i = 0; i < n; ++i) {
    if (Count[i] == 0) {
      Count[i] = top; top = i;
    }
  }
  for (i = 0; i < n; ++i) {
    k = top; if (k == -1) { flag = false; break; }
    top = Count[k]; temp = List[k]; out[len++] = k + 1;
    while (temp != NULL) {
      Count[temp->to]--;
      if (Count[temp->to] == 0) {
        Count[temp->to] = top; top = temp->to;
      } temp = temp->next;
    }
  }
  if (flag) {
    for (i = 0; i < len; ++i) {
      if (!i) printf("%d", out[i]); else printf(" %d", out[i]);
    } printf("\n");
  } else printf("Network has a cycle!\n");
  for (i = 0; i < n; ++i) {
    temp = List[i];
    while (temp) {
      List[i] = temp->next; delete temp; temp = List[i];
    }
  }
}
int main(void){
#ifndef ONLINE_JUDGE
  freopen("topsort.in", "r", stdin);
#endif
  while (~scanf("%d%d", &n, &m)){
    if (m + n == 0) break;
    int u, v; ArcNode *temp;
    memset(Count, 0, sizeof(Count));
    memset(List, 0, sizeof(List));
    memset(out, 0, sizeof(out));
    for (i = 0; i < m; ++i){
      scanf("%d%d", &u, &v); u--; v--;
      temp = new ArcNode; temp->next = NULL; temp->to = v;
      temp->next = List[u]; List[u] = temp; Count[v]++;
    }
    topsort();
  }

  return 0;
}

      用数组实现的链式栈 ,好神奇……

comments powered by Disqus