sekia #9415(2009/07/25 09:02 GMT) [ Perl ] Rating0/0=0.00
map万歳! 最悪計算量はO(N!)のはず。 お題に挙げられている単語リストだと110語あたりが限界です。 $ time perl doukaku227.pl fam55_40.txt 100 セイギハ -> ハゲヤマ -> マヤカシ -> ショウワル -> ルイベツ -> ツジツマ -> マタシタ -> タチノミ -> ミズヒキ -> キャクアシ -> シャクナゲ -> ゲレツサ -> サンバシ -> シールド -> ドウナガ -> ガイユウ -> ウワバリ -> リンセツ -> ツユザム -> ムスビメ -> メイフク real 0m0.585s user 0m0.561s sys 0m0.012s
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
#!/usr/bin/env perl use strict; use warnings; use utf8; use List::Util qw/reduce/; my @katakanas = split //, 'アイウエオカキクケコガキグゲゴサシスセソ' . 'ザジズゼゾタチツテトダヂヅデドナニヌネノ' . 'ハヒフヘホバビブベボパピプペポマミムメモ' . 'ヤユオワヲン'; sub head_and_tail($) { my $word = shift; $word =~ tr/ァィゥェォッャュョヮ/アイウエオツヤユヨワ/; $word =~ s/ー$//; (substr($word, 0, 1), substr($word, -1, 1)); } sub longest_chain(\%;$); sub longest_chain(\%;$) { no warnings qw/recursion/; my ($dict, $word) = @_; my @words = defined $word ? ($word) : map { map { $_->[0] } values %$_ } values %$dict; reduce { @$a > @$b ? $a : $b; } ([], map { my $word = $_; my (undef, $next_head) = head_and_tail $word; map { my $available_words = $dict->{$next_head}{$_}; my $next_word = pop @$available_words; my $chain = longest_chain(%$dict, $next_word); push @$available_words, $next_word; unshift @$chain, $word; $chain; } grep { @{ $dict->{$next_head}{$_} } } keys %{ $dict->{$next_head} }; } @words); } binmode STDOUT, ':utf8'; open my $words_file, '<:encoding(shiftjis)', shift or die $!; my @words = (map { chomp; split /\s+/ } <$words_file>); $#words = shift() - 1 if @ARGV; my %dict; for my $word (@words) { my ($head, $tail) = head_and_tail $word; $dict{$head}{$tail} = [] unless exists $dict{$head}{$tail}; push @{ $dict{$head}{$tail} }, $word; } local ($,, $\) = (' -> ', "\n"); print @{ longest_chain(%dict) };
Rating0/0=0.00-0+
[ reply ]
sekia #9415() [ Perl ] Rating0/0=0.00
Rating0/0=0.00-0+
[ reply ]