poj 1270

来源:互联网 发布:阿里云免费邮箱 - 百度 编辑:程序博客网 时间:2024/04/29 15:04

拓扑排序

#include <iostream>#include <cstdio>#include <cstring>#include <string>#include <algorithm>const int maxn = 30;using namespace std;int node[maxn],edge[maxn][maxn],ind[maxn],path[maxn];//节点,边,入度,路径bool flag[maxn];//标记是否访问int len;void Toposort(int pos){    if(pos == len){       for(int i = 0; i < len; ++i)         printf("%c",path[i]+'a');         putchar('\n');         return ;    }    for(int i = 0; i < len; ++i){       if(!flag[node[i]] && ind[node[i]] == 0){         flag[node[i]] = true;         path[pos] = node[i];         for(int j = 0; j < len; ++j)            if(edge[node[i]][node[j]] == 1)               ind[node[j]]--;       Toposort(pos + 1);       flag[node[i]] = false;       for(int j = 0; j < len; ++j)            if(edge[node[i]][node[j]] == 1)               ind[node[j]]++;    }  }}int main(){    string s;    while(getline(cin,s)){          memset(flag,false,sizeof(flag));          memset(ind,0,sizeof(ind));          memset(edge,0,sizeof(edge));          len = 0;          for(string::size_type i = 0; i != s.length(); ++i)              if(s[i] != ' ')                node[len++] = s[i] - 'a';          sort(node,node+len);         getline(cin,s);         int cnt=0,temp[2];         for(string::size_type i = 0; i != s.length(); ++i){              if(s[i] != ' '){                  temp[cnt++] = s[i] - 'a';                if(cnt == 2){                      edge[temp[0]][temp[1]] = 1;                      ind[temp[1]]++;                      cnt = 0;                  }              }          }          //cout<<len<<endl;         Toposort(0);         putchar('\n');    }    return 0;}


原创粉丝点击