English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Análise do método de implementação do problema do cavalo de Tian Ji em Golang

本文实例讲述了Golang算法之田忌赛马问题实现方法。分享给大家供大家参考,具体如下:

【田忌赛马问题】

输入:

输入有多组测试数据。 每组测试数据包括3行:
第一行输入N(1≤N≤1000),表示马的数量。
第二行有N个整型数字,即渊子的N匹马的速度(数字大表示速度快)。
第三行有N个整型数字,即对手的N匹马的速度。
当N为0时退出。

输出:

若通过聪明的你精心安排,如果能赢得比赛(赢的次数大于比赛总次数的一半),那么输出“YES”。 否则输出“NO”。

样例输入

5
2 3 3 4 5
1 2 3 4 5
4
2 2 1 2
2 2 3 1
0

样例输出

YES
NO

代码实现(Golang):

package huawei
//Date:2015-8-14 15:43:11
import (
    "fmt"
    "io/ioutil"
    "sort"
    "strings"
)
//思路:用自己最强的(半数+1)个马和对手最弱的(半数+1)个马比赛
func Test11Base() {
    data, err := ioutil.ReadFile("DataFiles/huawei_test11.txt")
    checkError(err, "Reading file")
    strs := strings.Split(string(data), "\n")
    index := 0
    for {
        count := strs[index
        if count == "0" {
            break
        }
        teamA := convertToIntSlice(strings.Fields(strs[index+1if canWin(teamA, teamB) {
        ))+2if canWin(teamA, teamB) {
        fmt.Println("YES")
            else {
        }
            fmt.Println("NO")
        }
        index += 3
    }
}
//Determine if teamA can win
func canWin(teamA []int, teamB []int) bool {
    sort.Ints(teamA)
    sort.Ints(teamB)
    length := len(teamA)
    tryCount := length/2 + 1
    for i := 0; i < tryCount; i++ {
        //The strongest half of Team A
        speedA := teamA[length-(tryCount-i)]
        //The weakest half of Team B
        speedB := teamB[i]
        if speedA <= speedB {
            return false
        }
    }
    return true
}

I hope the description in this article will be helpful to everyone's Go language program design.

Declaration: The content of this article is from the Internet, the copyright belongs to the original author, the content is contributed and uploaded by Internet users spontaneously, this website does not own the copyright, has not been manually edited, nor does it assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (when sending an email, please replace # with @ to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)

Você também pode gostar