#!/usr/bin/env tclsh9.0 namespace import ::tcl::mathfunc::int namespace import ::tcl::mathop::+ set acost 3 set bcost 1 proc nextmachine {} { if {[gets stdin line] < 0} {return [list]} if {$line eq ""} { if {[gets stdin line] < 0} {return [list]} } regexp {(\d+)\D+(\d+)} $line -> ax ay gets stdin line regexp {(\d+)\D+(\d+)} $line -> bx by gets stdin line regexp {(\d+)\D+(\d+)} $line -> px py list $ax $ay $bx $by [+ $px 10000000000000] [+ $py 10000000000000] } proc price {machine} { global acost bcost lassign $machine ax ay bx by px py # solve for integers A and B: # A*ax + B*bx = px , A*ay + B*by = py , 0 <= A <= 100 , 0 <= B <= 100 # A*ax*by + B*bx*by = px*by , A*ay*bx + B*by*bx = py*bx # A*ax*by - A*ay*bx = px*by - py*bx # A = (px*by - py*bx) / (ax*by - ay*bx) # A*ax*ay + B*bx*ay = px*ay , A*ay*ax + B*by*ax = py*ax # B*bx*ay - B*by*ax = px*ay - py*ax # B = (px*ay - py*ax) / (bx*ay - by*ax) set A [expr {($px*$by - $py*$bx) / ($ax*$by - $ay*$bx)}] set B [expr {($px*$ay - $py*$ax) / ($bx*$ay - $by*$ax)}] # puts "ax=$ax ay=$ay bx=$bx by=$by px=$px py=$py A=$A B=$B" # if {$A < 0 || $A > 100 || $B < 0 || $B > 100} {return 0} if {[expr {$A*$ax + $B*$bx}] != $px} {return 0} if {[expr {$A*$ay + $B*$by}] != $py} {return 0} expr {$A*$acost + $B*$bcost} } set total 0 while 1 { set m [nextmachine] if {! [llength $m]} break incr total [price $m] } puts $total