-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathA23.php
More file actions
42 lines (35 loc) · 983 Bytes
/
A23.php
File metadata and controls
42 lines (35 loc) · 983 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?php
fscanf(STDIN, "%d %d", $N, $M);
// クーポンごとのビットマスクを作成
$coupons = [];
for ($i = 0; $i < $M; $i++) {
$line = trim(fgets(STDIN));
$items = array_map('intval', explode(" ", $line));
$bit = 0;
for ($j = 0; $j < $N; $j++) {
if ($items[$j] == 1) {
$bit |= (1 << $j);
}
}
$coupons[] = $bit;
}
$goal = (1 << $N) - 1; // すべての品目が揃った状態
$visited = array_fill(0, 1 << $N, false);
$queue = new SplQueue();
$queue->enqueue([0, 0]); // [現在の状態, 使用したクーポン数]
$visited[0] = true;
while (!$queue->isEmpty()) {
list($state, $count) = $queue->dequeue();
if ($state === $goal) {
echo $count . PHP_EOL;
exit;
}
foreach ($coupons as $coupon) {
$next = $state | $coupon;
if (!$visited[$next]) {
$visited[$next] = true;
$queue->enqueue([$next, $count + 1]);
}
}
}
echo -1 . PHP_EOL;