AcWing 343. 排序
原题链接
简单
作者:
zqc
,
2021-04-02 14:11:57
,
所有人可见
,
阅读 368
go语言实现
package main
import "fmt"
var(
n int
m int
)
const N int = 30
var g [N][N]bool
var dist [N][N]bool
var st [N]bool
func floyd(){
for i := 0; i < n; i ++{
for j := 0; j < n; j ++{
dist[i][j] = g[i][j]
}
}
for k := 0; k < n; k ++{
for i := 0; i < n; i ++{
for j := 0; j < n; j ++{
dist[i][j] = dist[i][j] || (dist[i][k] && dist[k][j])
}
}
}
}
func check() int{
for i := 0; i < n; i ++{
if dist[i][i]{
return 2
}
}
for i := 0; i < n; i ++{
for j := 0; j < i; j ++{
if !dist[i][j] && !dist[j][i]{
return 0
}
}
}
return 1
}
func get_min() byte{
for i := 0; i < n; i ++{
if !st[i]{
flag := true
for j := 0; j < n; j ++{
if !st[j] && dist[j][i]{
flag = false
break
}
}
if (flag){
st[i] = true
return byte('A' + i)
}
}
}
return 'A'
}
func main(){
for fmt.Scanf("%d%d", &n, &m);n != 0 && m != 0;fmt.Scanf("%d%d", &n, &m){
for i := 0; i < n; i ++{
for j := 0; j < n; j ++{
g[i][j] = false
}
}
var(
temp int = 0
t int
)
for i := 1; i <= m; i ++{
var s string
fmt.Scanf("%s", &s)
a, b := s[0] - 'A', s[2] - 'A'
if (temp == 0){
g[a][b] = true
floyd()
temp = check()
if (temp != 0){
t = i
}
}
}
if temp == 0{
fmt.Printf("Sorted sequence cannot be determined.\n")
} else if temp == 2{
fmt.Printf("Inconsistency found after %d relations.\n", t)
} else{
for i := 0; i < n; i ++{
st[i] = false
}
fmt.Printf("Sorted sequence determined after %d relations: ", t)
for i := 0; i < n; i ++{
fmt.Printf("%c", get_min())
}
fmt.Printf(".\n")
}
}
}