fork download
  1. def check(xs,r)
  2. ts=[[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8]]
  3. zs=ts.map{|p1,p2,p3|
  4. (xs[p1]+xs[p2]+xs[p3])%xs[9]
  5. }
  6. if zs.min==zs.max && zs.min==r then
  7. return 1
  8. else
  9. return 0
  10. end
  11. end
  12. def check2(xs,ps,num)
  13. r=(xs[ps[0]]+xs[ps[1]]+xs[ps[2]])%xs[9]
  14. if num==-1 then
  15. return r
  16. end
  17. if r==num then
  18. return r
  19. end
  20. return -1
  21. end
  22. def dfs(deep,xs,ys,ps,cs,r)
  23. if deep==4 then
  24. r=check2(xs,[0,4,8],-1)
  25. end
  26. if deep==6 then
  27. return 0 if check2(xs,[2,4,6],r)!=r
  28. end
  29. if deep==7 then
  30. return 0 if check2(xs,[0,1,2],r)!=r
  31. end
  32. if deep==10 then
  33.  
  34. return check(xs,r)
  35. else
  36. res=0
  37. p1=ps[deep]
  38. if ys.size>0 && xs[p1]==0 then
  39. ys.size.times{|i|
  40. next if ys[i]==0
  41. xs[p1]=ys[i]
  42. t=ys[i]
  43. ys[i]=0
  44. if deep==0 && t==1 then
  45. res+=cs[ys.size-1]
  46. else
  47. res+=dfs(deep+1,xs,ys,ps,cs,r)
  48. end
  49. ys[i]=t
  50. xs[p1]=0
  51. }
  52. end
  53. if xs[p1]>0 then
  54.  
  55. if xs[p1]==1 && deep==0 then
  56. return cs[9]
  57. end
  58. res+=dfs(deep+1,xs,ys,ps,cs,r)
  59. end
  60. return res
  61. end
  62. end
  63. def f(xs)
  64. ys=[]
  65. cs=[1]
  66. ps=[9,0,4,8,2,6,1,3,5,7]
  67. m=1
  68. 1.upto(10){|e|
  69. ys<<e if xs.member?(e)==false
  70. m*=e
  71. cs<<m
  72. }
  73. puts dfs(0,xs,ys,ps,cs,-1)
  74. end
  75.  
  76. while true
  77. xs=gets.split(" ").map{|e| e.to_i}
  78. break if xs[0]==-1
  79. f(xs)
  80. end
Success #stdin #stdout 1.63s 8040KB
stdin
3 1 6 8 10 7 0 0 2 5
0 0 0 0 0 0 0 0 0 1
3 1 6 8 10 7 4 9 2 5
6 4 3 2 7 1 8 9 10 5
1 2 3 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 3
0 0 0 0 0 0 0 0 0 5
0 0 0 0 0 0 0 0 0 0
0 0 0 7 0 0 2 0 0 10
6 0 4 0 0 3 0 10 7 0
0 4 8 5 0 0 0 3 1 0
9 6 0 0 0 10 2 5 1 3
0 3 1 0 5 0 2 0 10 4
0 4 8 10 6 3 5 1 0 2
5 9 0 0 3 4 0 10 6 0
0 0 0 9 7 5 6 3 8 2
4 9 7 8 10 2 3 6 0 0
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1
stdout
2
362880
1
0
0
0
128
365896
1
24
0
0
0
0
6
2
2