这题就是朴素的拓扑排序,只是一开始题意没看清楚,不太清楚几种结果的优先级。
优先级其实就是给的测试数据的结果。
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<queue> #define Maxn 102 #define Maxm 10010 using namespace std; int graphic[Maxn][Maxn],indegree[Maxn],n,m,e; char ans[Maxn]; int Topsort() { int i,j,k,num,temp,f=0; temp=0; for(i=1;i<=n;i++) { num=0; for(j=1;j<=n;j++) { if(indegree[j]==0) num++; } if(num>1) f=1; for(j=1;j<=n;j++) { if(indegree[j]==0) { indegree[j]--; ans[e++]=j+'A'-1; for(k=1;k<=n;k++) { if(graphic[j][k]) indegree[k]--; } temp++; break; } } } //cout<<"*"<<temp<<endl; if(temp<n) return -1; if(f) return 0; return 1; } int main() { int i,j,a,b; char str[Maxm][10]; //freopen("ans.txt","w",stdout); while(scanf("%d%d",&n,&m)!=EOF,n||m) { memset(graphic,0,sizeof(graphic)); memset(indegree,0,sizeof(indegree)); e=0; int temp,pos; for(i=0;i<m;i++) { scanf("%s",&str[i]); memset(indegree,0,sizeof(indegree)); memset(graphic,0,sizeof(graphic)); for(j=0;j<=i;j++) { if(!graphic[str[j][0]-'A'+1][str[j][2]-'A'+1]) { indegree[str[j][2]-'A'+1]++; graphic[str[j][0]-'A'+1][str[j][2]-'A'+1]=1; } } e=0; temp=Topsort(); if(temp==1) { //cout<<e<<endl; pos=i+1; ans[e]='