コード例 #1
0
<?php

$inputFile = fopen("mark_and_toys.txt", "r") or die("Unable to open file!");
$data = array();
while (!feof($inputFile)) {
    $data[] = trim(fgets($inputFile));
}
fclose($inputFile);
echo greedy($data[0], $data[1]), "\n";
function greedy($price, $prices)
{
    $result = 0;
    $t = explode(" ", $price);
    $price = $t[1];
    $prices = explode(" ", $prices);
    sort($prices);
    $i = 0;
    foreach ($prices as $p) {
        $result += $p;
        if ($result > $price) {
            break;
        }
        $i++;
    }
    return $i;
}
コード例 #2
0
ファイル: two_arrays.php プロジェクト: eltonoliver/Algorithms
<?php

$inputFile = fopen("two_arrays.txt", "r") or die("Unable to open file!");
$data = array();
while (!feof($inputFile)) {
    $data[] = trim(fgets($inputFile));
}
fclose($inputFile);
$n = $data[0];
$j = 0;
for ($i = 0; $i < $n; $i++) {
    echo greedy($data[$j + 1], $data[$j + 2], $data[$j + 3]), "\n";
    $j = $j + 3;
}
function greedy($nk, $a, $b)
{
    $t = explode(" ", $nk);
    $n = $t[0];
    $k = $t[1];
    $a = explode(" ", $a);
    $b = explode(" ", $b);
    $result = $a;
    sort($b);
    for ($i = 0; $i < $n; $i++) {
        $find = $k - $b[$i];
        sort($result);
        foreach ($result as $key => $value) {
            if ($find < 0) {
                unset($result[0]);
                break;
            }