题目的意思是给你一个偏序关系集,问这个关系是否是良序的。使用了拓扑排序。
#include <stdio.h>

int map[26][26];
int op_m[26][26];

int count[26];
int op_c[26];

char road[26];
int len;

int que[1000];
int head, tail;

void initq ()


{
head = 0;
tail = -1;
}

void inq ( int *in )


{
que[++tail] = *in;
}

void outq ( int *out )


{
*out = que[head++];
}

int gets ()


{
return tail - head + 1;
}

void init ( int n )


{
for ( int i=0; i<n; i++ )

{
for ( int j=0; j<n; j++ )

{
map[i][j] = 0;
}
count[i] = 0;
}
}

void cpy ( int n )


{
for ( int i=0; i<n; i++ )

{
for ( int j=0; j<n; j++ )

{
op_m[i][j] = map[i][j];
}
op_c[i] = count[i];
}
}

void add ( char a, char b )


{
if ( ! map[ a-'A' ][ b-'A' ] )

{
map[ a-'A' ][ b-'A' ] = 1;
count[ b-'A' ] ++;
}
}


int sort ( int n ) /**//*排序返回结果:1成功, 0有环,-1有多种情况*/


{
int out;
int flag = 1;
len = 0;
initq ();
cpy ( n );
for ( int i=0; i<n; i++ )

{
if ( ! op_c[i] )

{
inq ( &i );
op_c[i] = -1;
}
}
while ( gets () )

{
if ( gets () > 1 )

{
flag = 0;
len = 0;
}
outq ( &out );
if ( flag )

{
road[len++] = out + 'A';
}
for ( int i=0; i<n; i++ )

{
if ( op_m[out][i] )

{
op_m[out][i] = 0;
op_c[i] --;
}
}
for ( i=0; i<n; i++ )

{
if ( ! op_c[i] )

{
inq ( &i );
op_c[i] = -1;
}
}
}

flag = 1;
for ( i=0; i<n; i++ )

{
if ( op_c[i] > 0 )

{
flag = 0;
break;
}
}
if ( ! flag )

{
return 0;
}
if ( len < n )

{
return -1;
}
return 1;
}

int main ()


{
int n, m;
char in[5];
int flag;
int ans;
while ( scanf ( "%d%d", &n, &m ) != EOF )

{
if ( n==0 && m ==0 )

{
break;
}

init ( n );
flag = 1;
for ( int i=0; i<m; i++ )

{
scanf ( "%s", &in );
if ( ! flag )

{
continue;
}
if ( in[0] == in[2] )

{
printf ( "Inconsistency found after %d relations.\n", i+1 );
flag = 0;
}
else

{
add ( in[0], in[2] );
ans = sort ( n );
if ( ! ans )

{
printf ( "Inconsistency found after %d relations.\n", i+1 );
flag = 0;
}
else if ( ans == 1 )

{
road[len] = '\0';
printf ( "Sorted sequence determined after %d relations: %s. \n", i+1, road );
flag = 0;
}
}
}
if ( flag )

{
printf ( "Sorted sequence cannot be determined.\n" );
}
}
return 0;
}


地址:
http://acm.pku.edu.cn/JudgeOnline/problem?id=1094