本文實(shí)例講述了Golang算法之田忌賽馬問(wèn)題實(shí)現(xiàn)方法。分享給大家供大家參考,具體如下:
【田忌賽馬問(wèn)題】
輸入:
輸入有多組測(cè)試數(shù)據(jù)。 每組測(cè)試數(shù)據(jù)包括3行:
第一行輸入N(1≤N≤1000),表示馬的數(shù)量。
第二行有N個(gè)整型數(shù)字,即淵子的N匹馬的速度(數(shù)字大表示速度快)。
第三行有N個(gè)整型數(shù)字,即對(duì)手的N匹馬的速度。
當(dāng)N為0時(shí)退出。
輸出:
若通過(guò)聰明的你精心安排,如果能贏得比賽(贏的次數(shù)大于比賽總次數(shù)的一半),那么輸出“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
代碼實(shí)現(xiàn)(Golang):
//Date:2015-8-14 15:43:11
import (
"fmt"
"io/ioutil"
"sort"
"strings"
)
//思路:用自己最強(qiáng)的(半數(shù)+1)個(gè)馬和對(duì)手最弱的(半數(shù)+1)個(gè)馬比賽
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組最強(qiáng)的一半
speedA := teamA[length-(tryCount-i)]
//B組最弱的一半
speedB := teamB[i]
if speedA <= speedB {
return false
}
}
return true
}
希望本文所述對(duì)大家Go語(yǔ)言程序設(shè)計(jì)有所幫助。