题目大意:将字母按照所给的序列从小到大输出。
算法思路:首先判断该图是否存在环,如果不存在,看能否进行有序输出,如果有序则后面的处理步骤都可以跳过,否则输出题目所给的话。
#include<iostream>
#include<string>
using namespace std;
int n,m,indegree[30],map[30][30];
char ans[30];
int topusort()
{
int temp[30],sym=0,i,j,m,flag,res=1;
for(i=0;i<n;i++)
{
temp[i]=indegree[i];
}
for(i=0;i<n;i++)
{
m=0;
for(j=0;j<n;j++)
{
if(temp[j]==0)
{
m++;
flag=j;
}
}
if(m==0)//说明有环
return 0;
if(m>1)
res=-1;
ans[sym++]=flag+'A';
temp[flag]=-1;
for(j=0;j<n;j++)
{
if(map[flag][j]>0)
temp[j]--;
}
}
return res;
}
int main()
{
int i,j,sign;
string s;
while(scanf("%d%d",&n,&m)&&(n!=0||m!=0))
{
sign=0;
memset(ans,0,sizeof(ans));
memset(map,0,sizeof(map));
memset(indegree,0,sizeof(indegree));
for(i=1;i<=m;i++)
{
cin>>s;
if(sign)
continue;
int x=s[0]-'A';
int y=s[2]-'A';
map[x][y]=1;
indegree[y]++;
int ss=topusort();
if(ss==0)//有环
{
cout<<"Inconsistency found after "<<i<<" relations."<<endl;
sign=1;
}
if(ss==1)//有序
{
cout<<"Sorted sequence determined after "<<i<<" relations: ";
for(j=0;j<n;j++)
{
cout<<ans[j];
}
cout<<"."<<endl;
sign=1;
}
}
if(!sign)
cout<<"Sorted sequence cannot be determined."<<endl;
}
}

被折叠的 条评论
为什么被折叠?



