赛船时间到了。你每将船压低一毫秒,它的速度就会每秒增加一毫米。就像《生死时速》中的巴士一样,船永远不会减速。
第一部分
输入格式:
 Time: 7 15 30
 Distance: 9 40 200
每列都是一场比赛,其中包含比赛时间和船只获胜所需行驶的距离。因此,在第一场比赛中,按住船两、三、四和五毫秒,船就可以行驶所需的距离 (9)。这是一些数学:
 $time = 7 ;
 $distance = 9 ;
 $testSeconds = 2 ;
 $newDistance = $testSeconds * ( $time - $current ) ;
 $canWin = $newDistance > $distance ;
 // $canWin = true
对于每场比赛,我都会根据时间生成一系列数字进行测试,然后根据该比赛的距离检查这些数字是否可以获胜。
 $extract = function ( $input ) {
 return array_values ( array_filter ( explode ( ' ' , explode ( ':' , $input ) [ 1 ] ) ) ) ;
 } ;
 [ $times , $distances ] = explode ( "\n" , $input ) ;
 $times = $extract ( $times ) ;
 $distances = $extract ( $distances ) ;
 $wins = [ ] ;
 foreach ( $times as $race => $time ) {
 $distance = $distances [ $race ] ;
 $range = range ( 1 , $time ) ;
 $winCount = 0 ;
 foreach ( $range as $r )
 {
 $newDistance = $r * ( $time - $r ) ;
 $canWin = $newDistance > $distance ;
 if ( $canWin )
 {
 $winCount ++ ;
 }
 }
 $wins [ ] = $winCount ;
 }
 echo 'Total is ' . array_product ( $wins ) . PHP_EOL ;
总分正确,第一部分完成。十分简单。
第二部分
显然,输入内容所写的纸上的字距调整不好,而且实际上只是一场比赛,而不是多场比赛。 [1]现在我们有一场大型比赛:
 $time = 71530; $distance = 940200;
我关闭了提取器以删除所有空格并只给我两个数字(我将它们放入一个数组中,这样我就可以避免更改任何其他代码):
 $extract = function ( $input ) {
 return ( int ) str_replace ( ' ' , '' , explode ( ':' , $input ) [ 1 ] ) ;
 } ;
 [ $times , $distances ] = explode ( "\n" , $input ) ;
 $times = [ $extract ( $times ) ] ;
 $distances = [ $extract ( $distances ) ] ;
就像昨天一样,当我也在一些大数字上使用range时,我耗尽了内存。我确实给它添加了内存并且它起作用了,但我知道这个问题有一个简单的修复方法,所以我将range逻辑更改为while循环。
 foreach ( $times as $race => $time ) {
 $distance = $distances [ $race ] ;
 $winCount = 0 ;
 $current = 1 ;
 while ( $current < $time ) {
 $newDistance = $current * ( $time - $current ) ;
 $canWin = $newDistance > $distance ;
 if ( $canWin ) {
 $winCount ++ ;
 }
 $current ++ ;
 }
 $wins [ ] = $winCount ;
 }
 echo 'Total is ' . array_product ( $wins ) . PHP_EOL ;
那是第二部分。我不知道array_product效率如何,我可以只计算总数,而不是添加到数组中。
我的解决方案在 GitHub 上。
- 
代码出现的“故事”部分确实很重要。 ⤾