Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

我的代码用了拓朴和DFS,所有恶心数据都测试正确。。。。。!可它就是WA,哪位大侠帮我看看,感激不尽!

Posted by majuncheng at 2009-08-25 00:35:49 on Problem 1094

#include <cstdio>
#include <cstring>

int tp[30][30];
int Q[60],ord[30];

int in[30];
int post[30],pre[30];
int n,m,cnt,cntp;
int dfs(int s)
{
	int flag=1;
	pre[s]=cnt++; //前序标记
	for (int i=0;i<n;i++)
		if (tp[s][i])
	{
		if (pre[i]==-1) { flag=dfs(i); if(flag==0) return 0;}
		else if(post[i]==-1) return 0;
		}
	post[s]=cntp++;//后序标记,主要就是用它来判断回边
	return flag;
}
int main()
{
	char l,r,b;
	int d1,d2;
	int head,tail,time=0;
	while (scanf("%d%d",&n,&m))
	{
		if (n==0 && m==0 ) break;
		int ans=0;    //ans=1表示排序成功,2表示环存在,3表示不明序
		int count,i,num=0;
        int order=0,head,tail;

		for ( i=0;i<n;i++)
			for (int j=0;j<n;j++)
			    tp[i][j]=0;
		for ( i=0;i<n;i++)
			in[i]=-1;  //把入度初始化为-1,入度>=0来判断出现点数
	

		for ( count=1;count<=m;count++)
		{
		    
			scanf("%c",&l);
			while ( l<'A' || l>'Z') scanf("%c",&l);
		     scanf("%c%c",&b,&r);
			 if (ans==1 || ans==2) continue;
			 d1=l-'A';d2=r-'A';

			 if (!tp[d1][d2])//保证重复边不会出错
			 {
				 if (in[d2]==-1) { in[d2]=1;num++;}
				 else in[d2]++; 
				 tp[d1][d2]=1;
				 if (in[d1]==-1) { in[d1]=0; num++;}
			 }
			 
			 memset(post,-1,sizeof(post));
			 memset(pre,-1,sizeof(pre));

                         //用DFS来判断有无环
			 cnt=0;cntp=0;   
			 for (i=0;i<n;i++)
				 if (in[i]>=0 && pre[i]==-1)
					 if (!dfs(i))
					 { ans=2; time=count;break;}
			 //如果点数目齐了可以用拓扑排排看能不能排出来
             if (ans!=2 && num==n)
			 {
			 head=tail=0;
			 for ( i=0;i<n;i++)
				 if (in[i]==0)
					 Q[tail++]=i;

                ans=0;
				 while (tail>head)
				 {
					 if (tail-head>1) { ans=3; break;}
					 int k=Q[head++];
				 ord[order++]=k;
				 
				 for (int j=0;j<n;j++)
					 if (tp[k][j] )
					 {				
						 if (--in[j]==0)
							 Q[tail++]=j;
					 }
				 }
				 if (ans!=3) { ans=1; time=count;}
				
			 
		
			 }
			 
		}

		if (ans==0 && order<n) ans=3;  //如果点没有完全出现,肯定不明序
		switch(ans)
		{ 
		case 1:{
			printf("Sorted sequence determined after %d relations: ",time);
			for (int i=0;i<order;i++)
				printf("%c",'A'+ord[i]);
			printf(".\n");break;
			   }
		case 2:
			printf("Inconsistency found after %d relations.\n",time);break;
			   
		case 3:
			printf("Sorted sequence cannot be determined.\n");break;
		}

	}

		
	return 0;
}




Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator