poj1094_Sorting It All Out_拓扑排序

poj1094题目链接

有三种情况:

              1.有序

              2.无序

              3.有环

拓扑排序可以判断是否有环或有序,除此以外就是无序了。并且1,3情况下只要判断后之后的输入就无影响,2必须要把所有顶点遍历完后才能确定。

建议在把排序时候把每次入度为0的顶点输出调试一下,更有助与理解。

#include<stdio.h>
#include<string.h>
int map[26][26],indegree[26],q[26];
int TopSort(int n)
{
	int t=0,i,j,flag=1,temp[26],loc,vis;
	for(i=0;i<n;i++)
		 temp[i]=indegree[i];
	  	 
	for(i=0;i<n;i++)
	{
		vis=0;
		for(j=0;j<n;j++)
		{
	       if(temp[j]==0)
	       {
	          vis++;
	          loc=j;
	       }
		      		
		}

	  if(vis==0) return 0;
	  if(vis>1) flag=-1;
	  q[t++]=loc;
	  
	  temp[loc]=-1;
	  for(j=0;j<n;j++)
	     if(map[loc][j]==1)
	        temp[j]--;
	}

	return flag;
}

int main()
{
	int sign,n,m,i,j;
	while(scanf("%d%d",&n,&m)&&n+m)
	{ 
	char str[5];
		memset(map,0,sizeof(map));
		memset(indegree ,0,sizeof(indegree));
	
		sign=0;
		for(i=1;i<=m;i++)
		{
			
			scanf("%s",str);
			//gets(str);
			if(sign)continue; 
			int x=str[0]-'A';
			int y=str[2]-'A';
			map[x][y]=1;
			indegree[y]++;
			int s=TopSort(n);
			if(s==0)
			{
				
				printf("Inconsistency found after %d relations.\n",i);
			    sign=1;
			}
			if(s==1)
			{
						
				printf("Sorted sequence determined after %d relations: ",i) ;
				for(j=0;j<n;j++)
				   printf("%c",q[j]+'A');
				printf(".\n");
				sign=1;
			}
		}
		if(!sign)
		{
			printf("Sorted sequence cannot be determined.\n");
		}
	}
	return 0;
} 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值