所有拓扑序列

题目链接: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;
}

猜你喜欢

转载自blog.csdn.net/w112348/article/details/111214939