LoginSignup
3
3

More than 5 years have passed since last update.

柵を修理

Last updated at Posted at 2015-01-09

Fence Repair

PHP5.3で優先度つきキューが実装されています。

<?php
class FenceRepair{
    public static function calc(array $boards){
        if(count($boards) < 1){ return false; }
        if(count($boards) < 2){ return current($boards); }
        $cost = 0;

        // キューに突っ込む
        $queue = new SplPriorityQueue();
        foreach($boards as $val){
            // 取り出しは降順なので、昇順にするためにマイナス
            $queue->insert($val, -$val);
        }

        while(true){
            // 短い2本を取り出す
            $costt = $queue->extract() + $queue->extract();
            $cost += $costt;
            // キューが無くなったら終了
            if($queue->isEmpty()){
                return $cost;
            }
            // くっつけた後の板を挿入
            $queue->insert($costt, -$costt);
        }
    }
}

$totalcost = FenceRepair::calc([1,2,3,4,5]);

とっても簡単にできました。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3