给出变量列表和一组约束关系, 按字典序输出所有满足关系的拓扑序列. 由于考虑到数据可能有坑爹的情况, 所以用了比较保险一点的方法处理输入.
#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
using namespace std;
int map[30][30];
bool exict[30];
int count[30];
int C=0;
char seq[30];
void DFStopsort(int cut)
{
if(cut==C)
{
seq[cut]=0;
puts(seq);
return ;
}
else
{
for(int i=0;i<26;i++)
{
if(exict[i]&&count[i]==0)
{
seq[cut]='a'+i;
count[i]=-1;
for(int k=0;k<26;k++)
{
if(map[i][k]&&exict[k])
count[k]--;
}
DFStopsort(cut+1);
count [i]=0;
for(int k=0;k<26;k++)
{
if(map[i][k]&&exict[k])
count[k]++;
}
}
}
}
}
int main()
{
char tmp[50];
int f=1;
while(gets(tmp))
{
memset(map,0,sizeof(map));
memset(exict,0,sizeof(exict));
memset(count,0,sizeof(count));
memset(seq,0,sizeof(seq));
C=0;
for(int i=0;i<strlen(tmp);i++)
if(isalpha(tmp[i])&&!exict[tmp[i]-'a'])
{
exict[tmp[i]-'a']=1;
C++;
}
gets(tmp);
int c=-1;
for(int j=0;j<strlen(tmp);j++)
{
if(isalpha(tmp[j]))
{
if(c==-1){
c=tmp[j]-'a';
}
else{
if(!map[c][tmp[j]-'a'])
{
map[c][tmp[j]-'a']=1;
count [tmp[j]-'a']++;
}
c=-1;
}
}
}
if(!f)puts("");
f=0;
DFStopsort(0);
}
return 0;
}