本文實例講述了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):
//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+1]))
teamB := convertToIntSlice(strings.Fields(strs[index+2]))
if canWin(teamA, teamB) {
fmt.Println("YES")
} else {
fmt.Println("NO")
}
index += 3
}
}
//判斷teamA是否能夠勝利
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++ {
//A組最強的一半
speedA := teamA[length-(tryCount-i)]
//B組最弱的一半
speedB := teamB[i]
if speedA <= speedB {
return false
}
}
return true
}
希望本文所述對大家Go語言程序設計有所幫助。