java – 为什么这个代码适用于这个TopCoder问题?

前端之家收集整理的这篇文章主要介绍了java – 为什么这个代码适用于这个TopCoder问题?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我一直试图从HOURS开始考虑这个TopCoder问题并且无法找到一个完美的解决方案并且发现下面给出的那个疯狂地使用了!

我想弄清楚这个解决方案如何适用于给定的探测器?我怎么能原先想到它?在阅读完解决方案之后,我认为它是霍夫曼编码的一种变体,但这是我能得到的.我真的很着迷,想知道什么样的思路可以导致这个解决方案..

这是问题所在:
http://community.topcoder.com/stat?c=problem_statement&pm=11860&rd=15091

Fox Ciel has lots of homework to do. The homework consists of some
mutually independent tasks. Different tasks may take different amounts
of time to complete. You are given a int[] workCost. For each i,the
i-th task takes workCost[i] seconds to complete. She would like to
attend a party and meet her friends,thus she wants to finish all
tasks as quickly as possible.

The main problem is that all foxes,including Ciel,really hate doing
homework. Each fox is only willing to do one of the tasks. Luckily,
Doraemon,a robotic cat from the 22nd century,gave Fox Ciel a split
hammer: a magic gadget which can split any fox into two foxes.

You are given an int splitCost. Using the split hammer on a fox is
instantaneous. Once a hammer is used on a fox,the fox starts to
split. After splitCost seconds she will turn into two foxes — the
original fox and another completely new fox. While a fox is splitting,
it is not allowed to use the hammer on her again.

The work on a task cannot be interrupted: once a fox starts working on
a task,she must finish it. It is not allowed for multiple foxes to
cooperate on the same task. A fox cannot work on a task while she is
being split using the hammer. It is possible to split the same fox
multiple times. It is possible to split a fox both before and after
she solves one of the tasks.

Compute and return the smallest amount of time in which the foxes can
solve all the tasks.

这是我在link发现的解决方

import java.util.*; 

public class FoxAndDoraemon { 
  public int minTime(int[] workCost,int splitCost) { 
    PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); 

    for(int i : workCost) pq.offer(i); 

    while(pq.size()>=2) { 
      int i = pq.poll(); 
      int j = pq.poll(); 
      pq.offer(Math.max(i,j) + splitCost); 
    } 
    return pq.poll(); 

  } 
}

解决方法

首先,你会意识到`max(i,j)splitCost’背后的原因.不是吗?基本上,如果你有一只狐狸,你将它分成两只并独立完成每项任务.让我们称这个过程为“合并”.

现在假设我们有三个作业a,b和c,使得a> b> c.您可以合并(合并(a,b),c)或合并(合并(a,c),b)或合并(合并(b,a).算一算,你可以证明合并(merge(b,a)在这三者中最少.

您现在可以使用归纳来证明此解决方案适用于任意数量的作业(不仅仅是3个).

猜你在找的Java相关文章