-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path07.pl
66 lines (56 loc) · 1.17 KB
/
07.pl
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/perl -w
use strict;
my %BAG;
sub DFS {
my ($cur,$seen,$target) = @_;
print "CUR = $cur SEEN = ".join(',', keys %$seen)."\n";
$seen->{$cur} = 1;
my $nexts = $BAG{$cur} || [];
for my $n (@$nexts) {
next if ($seen->{$n});
if ($n eq $target) {
return 1;
}
if (DFS($n, $seen, $target)) {
return 1;
}
}
return 0;
}
sub DFSCount {
my ($cur,$seen) = @_;
print "CUR = $cur SEEN = ".join(',', keys %$seen)."\n";
#$seen->{$cur} = 1;
my $nexts = $BAG{$cur} || [];
my $sum = 1;
for my $n (@$nexts) {
my ($nb, $cnt) = @$n;
$sum += $cnt * DFSCount($nb, $seen)
}
return $sum;
}
while (<>) {
print;
chomp;
unless (m{^([\w\s]+\w)\s+bags contain (.+)\.$}o) {
print "ERR $_\n";
}
next if ($2 eq "no other bags");
my $out = $1;
my @inbags = split(/,\s*/,$2);
my @ret;
for my $inbag (@inbags) {
$inbag =~ m{(\d+) ([\w\s]+\w) bag(s?)};
push @ret, [$2, $1];
}
$BAG{$out} = \@ret;
}
while (my ($k,$v) = each %BAG) {
print "$k => ", join(',', @$v), "\n";
}
#my $c = 0;
#for my $b (keys %BAG) {
# $c += DFS($b, {}, "shiny gold")
#}
# print "$c\n";
print ((DFSCount("shiny gold", {})-1)."\n");