Golang + 优先队列

公司食堂

http://www.nowcoder.com/questionTerminal/601815bea5544f389bcd20fb5ebca6a8

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)
    }
}
全部评论

相关推荐

安静的鲸鱼offer...:神仙级别hr,可遇不可求,甚至他可能也是突然有感而发。只能说遇上是件幸事。
秋招开始捡漏了吗
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务