Order.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package main
  2. func main() {
  3. //order := []int {2,3,1}
  4. //pattern := [][]int {{2,2,0},{0,1,1},{1,1,0}}
  5. order := []int{2, 3, 1}
  6. pattern := [][]int{{2, 2, 0}, {0, 1, 2}, {0, 1, 0}, {1, 1, 0}}
  7. println(getMinRemaining(order, pattern))
  8. }
  9. // BFS 广度优先搜索
  10. type Item struct {
  11. sum int
  12. pattern []int
  13. }
  14. func getMinRemaining(order []int, pattern [][]int) int {
  15. total := 0
  16. for i := 0; i < len(order); i++ {
  17. total += order[i]
  18. }
  19. sumArr := make([]int, len(pattern))
  20. res := total
  21. var queue []Item
  22. for i := 0; i < len(pattern); i++ {
  23. matched := true
  24. for j := 0; j < len(pattern[i]); j++ {
  25. v := pattern[i][j]
  26. sumArr[i] += v
  27. if v > order[j] {
  28. matched = false
  29. }
  30. }
  31. if sumArr[i] != 0 && matched {
  32. queue = append(queue, Item{sumArr[i], pattern[i]})
  33. if res > total-sumArr[i] {
  34. res = total - sumArr[i]
  35. }
  36. }
  37. }
  38. for len(queue) > 0 {
  39. var newQueue []Item
  40. for _, item := range queue {
  41. for i, p := range pattern {
  42. routerSum := sumArr[i] + item.sum
  43. diff := total - routerSum
  44. if diff >= 0 {
  45. var newPattern []int
  46. for j := 0; j < len(order); j++ {
  47. pNo := p[j] + item.pattern[j]
  48. if pNo <= order[j] {
  49. newPattern = append(newPattern, pNo)
  50. }
  51. }
  52. if len(newPattern) == len(order) {
  53. if diff == 0 {
  54. return 0
  55. }
  56. newQueue = append(newQueue, Item{routerSum, newPattern})
  57. if diff < res {
  58. res = diff
  59. }
  60. }
  61. }
  62. }
  63. }
  64. queue = newQueue
  65. }
  66. return res
  67. }