main.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package main
  2. import (
  3. "fmt"
  4. )
  5. // IMPOSSIBLE is a really large number that means impossible
  6. const IMPOSSIBLE int = 100000
  7. func main() {
  8. var N int
  9. fmt.Scan(&N)
  10. for cid := 0; cid < N; cid++ {
  11. var M, V int
  12. fmt.Scan(&M, &V)
  13. n := (M + 1) / 2
  14. gate := make([]Pair, n)
  15. for i := 1; i < n; i++ {
  16. fmt.Scan(&gate[i]._1, &gate[i]._2)
  17. }
  18. dp := make([][]int, M+1)
  19. for i := range dp {
  20. dp[i] = make([]int, 2)
  21. if n <= i {
  22. var leaf int
  23. fmt.Scan(&leaf)
  24. if leaf == 0 {
  25. dp[i][1] = IMPOSSIBLE
  26. } else {
  27. dp[i][0] = IMPOSSIBLE
  28. }
  29. }
  30. }
  31. for i := n - 1; 0 < i; i-- {
  32. lc, rc := 2*i, 2*i+1
  33. change := []int{IMPOSSIBLE, IMPOSSIBLE} // The step to take when current gate changes
  34. if gate[i]._1 == 1 { // AND gate
  35. if gate[i]._2 == 1 {
  36. change[0], change[1] = maxInt(dp[lc][0], dp[rc][0], dp[lc][0]+dp[rc][0])+1, minInt(dp[lc][1], dp[rc][1])+1
  37. }
  38. dp[i][0] = minInt(change[0], minInt(dp[lc][0], dp[rc][0]))
  39. dp[i][1] = minInt(change[1], maxInt(dp[lc][1], dp[rc][1], dp[lc][1]+dp[rc][1]))
  40. } else { // OR gate
  41. if gate[i]._2 == 1 {
  42. change[0], change[1] = minInt(dp[lc][0], dp[rc][0])+1, maxInt(dp[lc][1], dp[rc][1], dp[lc][1]+dp[rc][1])+1
  43. }
  44. dp[i][0] = minInt(change[0], maxInt(dp[lc][0], dp[rc][0], dp[lc][0]+dp[rc][0]))
  45. dp[i][1] = minInt(change[1], minInt(dp[lc][1], dp[rc][1]))
  46. }
  47. }
  48. if dp[1][V] >= IMPOSSIBLE { // Note: int maybe int64 in 64bit platform, or int32
  49. fmt.Printf("Case #%d: IMPOSSIBLE\n", cid+1)
  50. } else {
  51. fmt.Printf("Case #%d: %d\n", cid+1, dp[1][V])
  52. }
  53. }
  54. }