#include
<
iostream
>
#include
<
stack
>
#include
<
vector
>
int
n, m;
int
degree[
26
];
int
data[
26
][
26
];
bool
exist[
26
];
std::vector
<
char
>
re;
int
length()
{
int
num
=
0
;
for
(
int
i
=
0
; i
<
n;
++
i )
if
( exist[i] )
num
++
;
return
num;
}
int
toplogicalsort()
{
std::stack
<
char
>
st;
int
*
d
=
new
int
[n];
re.clear ();
for
(
int
i
=
0
; i
<
n;
++
i )
d[i]
=
degree[i];
for
(
int
i
=
0
; i
<
n;
++
i )
if
( d[i]
==
0
&&
exist[i] )st.push(i);
bool
ok
=
true
;
while
(
!
st.empty() )
{
if
( (
int
)st.size ()
>
1
) ok
=
false
;
int
t
=
st.top ();
st.pop();
re.push_back ( t
+
'
A
'
);
for
(
int
i
=
0
; i
<
n;
++
i )
if
( data[i][t]
==
1
&&
exist[i] )
{
d[i]
--
;
if
( d[i]
==
0
) st.push (i);
}
}
int
len
=
length();
if
( (
int
)re.size ()
<
len )
return
2
;
//
exit circle
if
(
!
ok )
return
0
;
if
( (
int
)re.size ()
==
n )
return
1
;
return
0
;
}
int
main()
{
while
( scanf(
"
%d%d
"
,
&
n,
&
m), m
+
n
!=
0
)
{
memset( degree,
0
,
sizeof
(degree) );
memset( data,
0
,
sizeof
(data ) );
memset( exist,
false
,
sizeof
(exist) );
bool
isok
=
true
;
bool
determin
=
false
;
getchar();
for
(
int
i
=
1
; i
<=
m;
++
i )
{
char
a, b;
a
=
getchar();
getchar();
b
=
getchar();
getchar();
exist[a
-
'
A
'
]
=
true
;
exist[b
-
'
A
'
]
=
true
;
if
(
!
determin
&&
isok
&&
(data[a
-
'
A
'
][b
-
'
A
'
]
==
1
||
a
==
b) )
{
isok
=
false
;
printf(
"
Inconsistency found after %d relations.\n
"
, i);
}
if
( data[b
-
'
A
'
][a
-
'
A
'
]
==
0
) degree[b
-
'
A
'
]
++
;
data[b
-
'
A
'
][a
-
'
A
'
]
=
1
;
int
type;
if
(
!
determin
&&
isok
&&
(type
=
toplogicalsort()) )
{
if
( type
==
1
)
{
determin
=
true
;
printf(
"
Sorted sequence determined after %d relations:
"
, i );
for
( size_t x
=
0
; x
<
re.size ();
++
x )
printf(
"
%c
"
, re[x] );
printf(
"
.\n
"
);
}
else
if
( type
==
2
)
{
isok
=
false
;
printf(
"
Inconsistency found after %d relations.\n
"
, i);
}
}
}
if
(
!
determin
&&
isok ) printf(
"
Sorted sequence cannot be determined.\n
"
);
}
return
0
;
}
posted on 2008-10-03 01:35
Darren 阅读(229)
评论(0) 编辑 收藏 引用 所属分类:
图论