这道题着实让无数人纠结,wa了n次n天,poj的discuss有大量的数据,wa的同学可以试一试。
结果我把数据都过了还是wa,后来在discuss的帮助下终于ac了,判断是否有环要最先判断,例如如下的数据:
4 4
A<B
C<B
D<B
B<A
总的思想是拓扑排序,我的方法比较笨,先不完全拓扑排序判断有无环,在完全拓扑排序判断是否满足了条件:
#include<iostream>
#include<stdio.h>
#include<queue>
using namespace std;
int map[27][27];
int rudu[27];
int r_mark[27];
int fff; //一个分量中如度为0的点的个数
int chu; //一个分量中入度为零得点
int dfs(int m)
{
int i;
if(r_mark[m]==1)
return 0;
else
r_mark[m]=1;
if(rudu[m]==0)
{
fff++;
chu=m;
}
int k=0;
for(i=0;i<27;i++)
if((map[i][m]||map[m][i])&&r_mark[i]==0)
k+=dfs(i);
return k+1;
}
int main()
{
int m,n;
//freopen("out","w",stdout);
while(scanf("%d%d",&m,&n),m||n)
{
int i,j;
memset(map,0,sizeof(map));
memset(rudu,0,sizeof(rudu));
int rrr=0;
for(i=0;i<n;i++)
{
char str[10];
scanf("%s",str);
if(map[str[0]-'A'][str[2]-'A']==1)
continue;
map[str[0]-'A'][str[2]-'A']=1;
rudu[str[2]-'A']++;
int sum=0,k;
if(rrr)
continue;
for(j=0;j<m;j++)
{
if(rudu[j]==0)
{
sum++;
k=j;
}
}
if(sum==0)
{
printf("Inconsistency found after %d relations.\n",i+1);
rrr=1;
continue;
}
int ww_rudu[27]; //不完全拓扑排序证明无环
for(j=0;j<27;j++)
ww_rudu[j]=rudu[j];
j=0;
while(ww_rudu[j]!=0)
j++;
k=j;
int count=0;
while(1)
{
count++;
ww_rudu[k]=-1;
for(j=0;j<m;j++)
{
if(map[k][j])
{
ww_rudu[j]--;
}
}
j=0;
while(ww_rudu[j]!=0&&j<m)
j++;
k=j;
if(j==m)
break;
}
if(count<m)
{
printf("Inconsistency found after %d relations.\n",i+1);
rrr=1;
continue;
}
int jj;
memset(r_mark,0,sizeof(r_mark));
for(jj=0;jj<m;jj++)
{
if(r_mark[jj]==1)
continue;
fff=0;
queue<int> q;
int mm=dfs(jj);
if(mm==1)
continue;
if(fff==0)
{
printf("Inconsistency found after %d relations.\n",i+1);
rrr=1;
break;
}
int cc=0;
int mark=0;
int w_rudu[27];
for(j=0;j<27;j++)
w_rudu[j]=rudu[j];
int k=chu;
q.push(k);
int wa=0;
if(fff==1&&mm==m) //完全拓扑排序求解最终问题
while(1)
{
cc++;
//cout<<"aaaaaa"<<endl;
int sum=0,kk;
for(j=0;j<m;j++)
{
if(map[k][j])
{
w_rudu[j]--;
if(w_rudu[j]==0)
{
sum++;
kk=j;
}
}
}
if(sum==1)
{
k=kk;
q.push(k);
}
else
break;
}
// cout<<mark<<" "<<cc<<" "<<mm<<" "<<fff<<endl;
if(cc==m&&wa==0)
{
printf("Sorted sequence determined after %d relations: ",i+1);
while(!q.empty())
{
printf("%c",q.front()+'A');
q.pop();
}
printf(".\n");
rrr=1;
}
}
}
if(rrr==0)
{
printf("Sorted sequence cannot be determined.\n");
}
}
}