思路:
在有向图中将入度为0的节点依次分离出来。
如果最后不存在入度为0的节点,则说明有环,不存在拓扑排序,无解。
注意:如果按照字典序排序,则改用优先队列。
模板
queue<int>q;
vector<int>edge[n];
for(int i=0;i<n;i++) //n 节点的总数
if(in[i]==0) q.push(i); //将入度为0的点入队列
vector<int>ans; //ans 为拓扑序列
while(!q.empty())
{
int p=q.front(); q.pop(); // 选一个入度为0的点,出队列
ans.push_back(p);
for(int i=0;i<edge[p].size();i++)
{
int y=edge[p][i];
in[y]--;
if(in[y]==0)
q.push(y);
}
}
if(ans.size()==n)
{
for(int i=0;i<ans.size();i++)
printf( "%d ",ans[i] );
printf("\n");
}
else printf("No Answer!\n"); // ans 中的长度与n不相等,就说明无拓扑序列
#include <iostream>
#include <cstdio>
#include <cmath>
#include <queue>
#include <string>
#include <vector>
#include <set>
#define ll long long
using namespace std;
vector<int> a[105];
int in[105];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
string str;
set<char> s;
while(cin >> str)
{
s.insert(str[0]);
s.insert(str[2]);
if(str[1]=='>')
{
in[str[2]-'A']++;
a[str[0]-'A'].push_back(str[2]-'A');
}
else
{
in[str[0]-'A']++;
a[str[2]-'A'].push_back(str[0]-'A');
}
}
priority_queue<int,vector<int>,greater<int> > q;
for(int i=0;i<26;i++)
{
if(s.count(i+'A')&&in[i]==0)
q.push(i);
}
vector<int> res;
while(!q.empty())
{
int now=q.top();
q.pop();
res.push_back(now);
for(int i=0;i<a[now].size();i++)
{
int t=a[now][i];
in[t]--;
if(in[t]==0)
q.push(t);
}
}
if(s.size()==res.size())
{
for(int i=0;i<res.size();i++)
printf("%c",res[i]+'A');
printf("\n");
}
else
printf("No Answer!\n");
return 0;
}