题解思路:循环暴力每次的拓扑排序就行。
代码:
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<vector>
#include<cstring>
#include<set>
#include<queue>
using namespace std;
typedef long long ll;
#define inf 0x3f3f3f3f
const int mx = 26+5,mod = 1e9+7;
int n,m,in[mx],ret[mx],a[mx],size;
typedef long long ll;
char c[10];
vector <int> vec[mx];
int topo(int x){
queue<int>que;
que.push(x);
int ans = 1;
ret[size] = x;
while(!que.empty()){
int po = que.front(),cnt = 0;
que.pop();
for(int i=0;i<vec[po].size();i++){
int son = vec[po][i];
a[son]--;
if(!a[son]){
que.push(son);
size++,cnt++;
ret[size] = son;
}
}
if(cnt>1) ans = 0;
}
return ans;
}
int main(){
while(scanf("%d%d",&n,&m)&&n+m){
int ans = 0;
memset(in,0,sizeof(in));
for(int i=0;i<n;i++) vec[i].clear();
for(int i=1;i<=m;i++){
size = 0;
int flag = 0;
scanf("%s",c);
if(c[1]=='<') vec[c[2]-'A'].push_back(c[0]-'A'),in[c[0]-'A']++;
else vec[c[0]-'A'].push_back(c[2]-'A'),in[c[2]-'A']++;
if(ans) continue;
copy(in,in+n,a);
for(int j=0;j<n;j++)
if(!in[j]){
size++;
if(topo(j)) ans = i;
if(flag) ans = 0;
flag = 1;
}
if(size<n) ans = -i;
}
if(ans<0) printf("Inconsistency found after %d relations.\n",-ans);
else if(!ans) puts("Sorted sequence cannot be determined.");
else{
printf("Sorted sequence determined after %d relations: ",ans);
for(int i=n;i>=1;i--) putchar(ret[i]+'A');
puts(".");
}
}
return 0;
}