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

1094 TLE

Posted by nestle at 2005-06-22 12:06:41 on Problem 1094
我的思路是每次读入一个关系,先判断有没有环,再用拓扑排序,是不是这样每次先判断有没有环的缘故?高人能不能指点一下,不胜感激。
#include <iostream>
#include <cstdio>
#define N 26
using namespace std;
int rel[N][N+1];
int f[N];
int n,m;
char ans[N+1];

bool search(int j){
int i;
   for(i=1;i<=rel[j][0];i++){
      if(f[rel[j][i]])  return true;
      f[rel[j][i]]=1;
      if(search(rel[j][i]))  return true;
      f[rel[j][i]]=0;
   }    
   return false;
}    
bool havecircle(){
   int i;
   memset(f,0,sizeof(int)*n);
   for(i=0;i<n;i++){
      if(!f[i]&&rel[i][0]){
         f[i]=1;
         if(search(i))  return true;
         f[i]=0;
      }    
   }    
   return false;
}    

bool toposort(){
int deg[N];
int zero[N+1],flag[N],top;
int i,j,t,cnt;
   memset(deg,0,sizeof(int)*n); //初始化 
   for(i=0;i<n;i++){
      for(j=1;j<=rel[i][0];j++)  deg[rel[i][j]]++;
      flag[i]=0;   //初始化 
   }    
   for(i=0,top=0;i<n;i++){
      if(!deg[i])  zero[++top]=i;
   }    
   cnt=0;
   while(cnt<n){
      if(top==0||top>1)  break;
      t=zero[top];
      ans[cnt++]=t+'A';
      flag[t]=1;
      for(j=1;j<=rel[t][0];j++)  deg[rel[t][j]]--;
      for(i=0,top=0;i<n;i++){
         if(!flag[i]&&!deg[i])   zero[++top]=i;
      }    
   }    
   if(cnt>=n){
      ans[n]=0;
      return true;
   }    
   return false;
}    
int main(){
char a,ch,b;
int i,yes,k,j;
   while(cin>>n>>m&&(n||m)){
      for(i=0;i<n;i++)  rel[i][0]=0;
      for(i=1,yes=0;i<=m;i++){
         cin>>a>>ch>>b;
         if(yes!=0)  continue;
         k=a-'A';
         for(j=1;j<=rel[k][0];j++){
            if(rel[k][j]+'A'==b)  break;
         }                                 //判断这个关系以前有没有出现过 
         if(j>rel[k][0]){
            rel[k][++rel[k][0]]=b-'A';
            if(havecircle())  yes=-i;
            else if(toposort())  yes=i;    
         }    
      }    
      if(yes==0)  printf("Sorted sequence cannot be determined.\n");
      else if(yes>0)  printf("Sorted sequence determined after %d relations: %s.\n",yes,ans);
      else  printf("Inconsistency found after %d relations.\n",-yes);
   }       
   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