- 论坛徽章:
- 2
|
本帖最后由 miniqq 于 2011-03-25 14:32 编辑
回复 1# py
Hi, 我给出一个:
首先,我对题目的理解是: 给定一个数A, 从数组 B中找出几个数,使其和等于A,并且大数优先. 通常A比B中最大的数大.
说明,我省略了两个步骤: 把数组变为hash, 从大到小排列不重复的数组 @list.
脚本:
- #!/usr/bin/perl -w
- #
- use strict;
- my %hash = ();
- $hash{5} = 1;
- $hash{20} = 3;
- $hash{50} = 1;
- $hash{100} = 1;
- my $osum = 160;
- my $sum = $osum;
- my @list = (100,50,20,5);
- my %result;
- my @give;
- my $trys = scalar(@list);
- retry:
- foreach my $c (@list) {
- if ($sum >= $c and $sum > 0) {
- if ($hash{$c} == 1) {
- $sum = $sum - $c;
- $result{$c} = 1;
- push @give, $c;
- next;
- }
- elsif ($hash{$c} > 1) {
- my $i = 0;
- for($i=0, $i < $hash{$c}, ++$i) {
- if ($sum >= $c and $sum > 0) {
- $sum = $sum - $c;
- $result{$c}++;
- if ($result{$c} > $hash{$c}) {
- print "not found\n";
- exit 1;
- }
- push @give, $c;
- next;
- }
- }
- }
- }
- else {
- next;
- }
- }
- if ($sum > 0) {
- $sum = $osum;
- %result = ();
- my $last;
- if(scalar(@give) >=2) {
- pop @give;
- $last = pop @give;
- }
- else {
- $last = pop @give;
- }
- $trys--;
- if ($trys < 1 or !$last) {
- print "not found\n";
- exit 1;
- }
- @give = ();
- @list = grep (!/$last/, @list);
- goto retry;
- }
- if ($sum == 0) {
- foreach my $find (keys %result) {
- print "$find\t$result{$find}\n";
- }
- }
- else {
- print "not found\n";
- }
复制代码 觉得还不完善.不知哪里要改一下. |
|