GO版本优先队列实现
package main
import (
"container/heap"
"fmt"
)
type IntHeap []int
func (h IntHeap) Len() int { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x interface{}) {
*h = append(*h, x.(int))
}
func (h *IntHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
func calDinnerIndex(nums, people string) {
queue0 := make([]int, 0)
queue1 := &IntHeap{}
for i := range nums {
if nums[i] == '0' {
queue0 = append(queue0, i+1)
} else if nums[i] == '1' {
*queue1 = append(*queue1, i+1)
}
}
heap.Init(queue1)
for i := range people {
if people[i] == 'M' {
if len(*queue1) > 0 {
fmt.Println(heap.Pop(queue1))
} else if len(queue0) > 0 {
cur := queue0[0]
fmt.Println(cur)
queue0 = queue0[1:]
//queue1 = append(queue1, cur)
heap.Push(queue1, cur)
}
} else {
if len(queue0) > 0 {
cur := queue0[0]
fmt.Println(cur)
queue0 = queue0[1:]
//queue1 = append(queue1, cur)
heap.Push(queue1, cur)
} else if len(*queue1) > 0 {
fmt.Println(heap.Pop(queue1))
}
}
}
}
func main() {
t := 0
fmt.Scanln(&t)
for i := 0; i < t; i++ {
n, m := 0, 0
var nums, people string
fmt.Scanln(&n)
fmt.Scanln(&nums)
fmt.Scanln(&m)
fmt.Scanln(&people)
calDinnerIndex(nums, people)
}
} 
京公网安备 11010502036488号