1. 程式人生 > 其它 >所有拓撲序列

所有拓撲序列

技術標籤:課程_DSA演算法競賽

題目連結:1270:Following Orders
分析

  • 回溯法
  • 最壞複雜度為 O ( n ! ) O(n!) O(n!),也就是不含有向邊的圖,節點1~n的全排列
#include <iostream>
#include <cstring>
#include <algorithm>
#include <set>
using namespace std;

set<char> nodes;
int indeg[300];
bool vis[300];
int G[300][300]; // 鄰接矩陣

int N =
0; char rst[300]; // topological sort result void init() { nodes.clear(); memset(vis, 0, sizeof(vis)); memset(indeg, 0, sizeof(indeg)); memset(rst, 0, sizeof(rst)); memset(G, 0, sizeof(G)); } void dfs(int dep) { if (dep == N) { printf("%s\n", rst); return ;
} /* to decide current node c, traverse all the node in alphabet-order */ for (char c : nodes) { /* traverse previous nodes */ bool isok = 1; for (int j = 0; j < dep; ++j) /* current node shouldn't connect/equal to previous node */ if (G[c][rst[
j]] || rst[j] == c) { isok = 0; break; } if (!isok) continue; rst[dep] = c; dfs(dep+1); } } int main() { while (1) { init(); /* input */ char c, d; bool flag = 0; while ((c = getchar()) != EOF && c != '\n') { if (c == ' ') continue; nodes.insert(c); } if (c == EOF) break; while ((c = getchar()) != EOF && c != '\n') { if (c == ' ') continue; if (flag == 0) d = c, flag = 1; else { G[d][c] = 1; flag = 0; ++indeg[c]; } } N = nodes.size(); dfs(0); printf("\n"); } system("pause"); return 0; }