1

我正在 codechef 中尝试这个问题 - http://www.codechef.com/OCT12/problems/DRGNBOOL

这是我的解决方案

def array_sum(a)
    sum=0
    a.each do |x|
        sum=sum+x
    end
    return sum
end

number_of_test_cases=gets.to_i
number_of_test_cases.times do
    n_and_m=gets.split(" ")
    n=n_and_m[0].to_i
    m=n_and_m[1].to_i
    soints=Hash.new{|h, k| h[k]=[]}
    sofloats=Hash.new{|h, k| h[k]=[]}

    n.times do
        x=gets.split(" ")
        a=x.first.to_i
        b=x.last
        soints[b].push(a)
    end
    m.times do
        x=gets.split(" ")
        a=x.first.to_i
        b=x.last
        sofloats[b].push(a)
    end

    result=0
    soints.each_pair do |k, v|
        if v.size>1
            max_value=sofloats[k].max
            v.each do |val|
                if val<max_value
                    result=result+(max_value-val)
                    val=max_value
                end
            end
        end
        l=array_sum(v)
        k=array_sum(sofloats[k])
        if l<k
            result=result+(k-l)
        end
    end
    puts result
end

我在提交时收到“错误答案”。我的解决方案适用于给定的情况。任何人都可以提供我的解决方案失败的测试用例吗?

4

1 回答 1

2

编辑:我发现你的代码失败了。

1
2 1
10 1   
10 1
50 1
110 # => the right answer is 30

以防万一,这是我写的被接受的答案。

def get_ints
  gets.chomp.split.map(&:to_i)
end

def gather_warriors(count, hash)
  count.times do
    power, level = get_ints
    (hash[level] ||= []) << power
  end
end

test_cases_count = gets.chomp.to_i
test_cases = []

test_cases_count.times do
  soints = {}
  sofloats = {}
  soints_count, sofloats_count = get_ints

  gather_warriors(soints_count, soints)
  gather_warriors(sofloats_count, sofloats)

  test_cases << [soints, sofloats]
end

def run_test(soints, sofloats)
  needed_chakra = 0

  soints.keys.each do |level|
    soints_summed_power = soints[level].inject(&:+)
    sofloats_summed_power = sofloats[level].inject(&:+)

    needed_chakra += [0, sofloats_summed_power - soints_summed_power].max
  end

  puts needed_chakra
end

test_cases.each do |test_case|
  run_test(test_case.first, test_case.last)
end
于 2012-10-07T06:23:11.360 回答