非常有趣的一件事是今天在TopCoder的1000分题里面发现了这道经典数学问题。

Notes

          -                   In an optimal solution, exactly two people will be sent across the           bridge with the flashlight each time (if possible), and exactly one           person will be sent back with the flashlight each time. In other           words, in an optimal solution, you will never send more than one           person back from the far side at a time, and you will never send           less than two people across to the far side each time (when           possible).        

Constraints

          -                   times will have between 1 and 6 elements, inclusive.        
          -                   Each element of times will be between 1 and 100, inclusive.        

Examples

          0)                          
                      

{ 1, 2, 5, 10 }

Returns: 17

                      The example from the text.                    

          1)                          
                      

{ 1, 2, 3, 4, 5 }

Returns: 16

                      One solution is: 1 and 2 cross together (2min), 1 goes                       back (1min), 4 and 5 cross together (5min), 2 goes back                       (2min), 1 and 3 cross together (3min), 1 goes back                       (1min), 1 and 2 cross together (2min). This yields a                       total of 2 + 1 + 5 + 2 + 3 + 1 + 2 = 16 minutes spent.                    

          2)                          
                      

{ 100 }

Returns: 100

                      Only one person crosses the bridge once.                    

          3)                          
                      

{ 1, 2, 3, 50, 99, 100 }

Returns: 162

                             

计算的这道题方法其实类似于动态规划,关键在于寻找最优子结构

1)问题的最优子结构是这样推出的

  1.每一个人都得过河

  2.由1可以知道cost最大的一个也必须过河

  3.由2可知必然有一次过河的代价为cost(max)

  4.由3可知,在将cost最大的人送过河的运输中最优的方案是将cost第二大的人也同时过河

  因此问题可以转化为如何将cost第一大和第二大的两个人同时送过河

2)最优化问题的解法在于首先将cost最小的两个人先送过河然后选择其一送回手电筒(无论哪个人都一样),然后再使cost最大和第二大的两个人同时过河,再另上一次剩在另一  岸的cost最小或者次小的人送回手电筒

  因此每次将一对人送过河的cost=iMax1st+(iMin2nd+2*iMin1st)

3)按总人数的奇数偶数可以将整个问题循环之后分支为两个子问题(显而易见,不多赘述)

4)利用大根堆和小根堆使遍历的时间复杂度从n降低至logn

多次实验后代码如下(以下大部分是大根堆小根堆的搭建代码):

 #include<set>
#include<vector>
#include<set>
#include<vector>
#include<iostream> using namespace std; #define HEAP_SIZE 1024
//////////////////////////////////////////
template<typename T>
class MaxHeap{
T*arrData;
int top;
////////////Filters Up&Down void swap(T*l,T*r){
T temp=*l;
*l=*r;
*r=temp;
} //////////////////////////////////////////
void FilterUp(){
int kid=top-;
int parent=(kid-)/;
while(arrData[kid]>arrData[parent]){
swap(&arrData[kid],&arrData[parent]);
kid=parent;
parent=(parent-)/;
}
}
/////////////////////////////////////////
void FilterDown(){
int parent=;
int kid=arrData[parent*+]>arrData[parent*+]?parent*+:parent*+;
while(kid<top&&arrData[kid]>arrData[parent]){
swap(&arrData[kid],&arrData[parent]);
parent=kid;
kid=arrData[parent*+]>arrData[parent*+]?parent*+:parent*+;
}
}
public:
MaxHeap():top(){ arrData=new T[HEAP_SIZE]; }
~MaxHeap(){ delete arrData; } /////////////////////////////////////////////
////// Constractor & Destructor Above
/////////////////////////////////////////////
bool insert(T v){
if(top<HEAP_SIZE){
arrData[top]=v;
top++;
FilterUp();
return true;
}else return false;
} T remove(){
if(top){
int iTop=arrData[];
arrData[]=arrData[top-];
top--;
FilterDown();
return iTop;
}else return ;
}
}; //////////////////////////////////
template<typename T>
class MinHeap{
T*arrData;
int top;
////////////Filters Up&Down void swap(T*l,T*r){
T temp=*l;
*l=*r;
*r=temp;
} //////////////////////////////////////////
void FilterUp(){
int kid=top-;
int parent=(kid-)/;
while(arrData[kid]<arrData[parent]){
swap(&arrData[kid],&arrData[parent]);
kid=parent;
parent=(parent-)/;
}
}
/////////////////////////////////////////
void FilterDown(){
int parent=;
int kid=arrData[parent*+]<arrData[parent*+]?parent*+:parent*+;
while(kid<top&&arrData[kid]<arrData[parent]){
swap(&arrData[kid],&arrData[parent]);
parent=kid;
kid=arrData[parent*+]<arrData[parent*+]?parent*+:parent*+;
}
}
//////////////////////////////////////////////////////
public:
MinHeap():top(){ arrData=new T[HEAP_SIZE]; }
~MinHeap(){ delete arrData; } /////////////////////////////////////////////
////// Constractor & Destructor Above
///////////////////////////////////////////// bool insert(T v){
if(top<HEAP_SIZE){
arrData[top]=v;
top++;
FilterUp();
return true;
}else return false;
} T remove(){
if(top){
int iTop=arrData[];
arrData[]=arrData[top-];
top--;
FilterDown();
return iTop;
}else return ;
}
}; class BridgeCrossing{ void init(vector<int> v){
for(int i=;i<v.size();i++){
here.insert(v[i]);
here2.insert(v[i]);
}
} public:
MinHeap<int> here;
MinHeap<int> there;
MaxHeap<int> here2;
int minTime(vector<int> times){
int iTotal=;
init(times);
int max1st=-;
int max2nd=-;
int min1st=here.remove();
int min2nd=here.remove();
//////Returning Back
there.insert(min1st);
here.insert(min2nd);
while(true){
max1st=here2.remove();
if(max1st==min2nd)break;
max2nd=here2.remove();
if(max2nd==min2nd)break;
iTotal+=max1st+min1st+*min2nd;
}
if(max1st==min2nd){
iTotal+=min2nd;
return iTotal;
}else if(max2nd==min2nd){
iTotal+=min2nd+min1st+max1st;
return iTotal;
}else return -;
}
};

经典数学问题<手电过河问题>的动态解法--问题规模扩展至任意大小的更多相关文章

  1. css中height 100vh的应用场景,动态高度百分比布局,浏览器视区大小单位

    css中height 100vh的应用场景,动态高度百分比布局,浏览器视区大小单位 height:100vh 一些只能vw, vh才能完成的应用场景: 1. 场景之:元素的尺寸限制 vw vh 主要是 ...

  2. POJ 1845-Sumdiv【经典数学题目---求因子和】

    转载请注明出处:http://blog.csdn.net/lyy289065406/article/details/6648539 優YoU  http://user.qzone.qq.com/289 ...

  3. 动态规划之经典数学期望和概率DP

    起因:在一场训练赛上.有这么一题没做出来. 题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6829 题目大意:有三个人,他们分别有\(X,Y,Z\)块钱 ...

  4. 【转载】docker 应用之动态扩展容器空间大小

    docker 容器默认的空间是 10G, 如果想指定默认容器的大小(在启动容器的时候指定),可以在 docker 配置文件里通过 dm.basesize 参数指定,比如 docker -d --sto ...

  5. Activiti动态设置办理人扩展

    关键词:Assignee.Candidate users.Candidate groups:setAssignee.taskCandidateUser.taskCandidateGroup 主要解决问 ...

  6. javascript生成表格增删改查 JavaScript动态改变表格单元格内容 动态生成表格 JS获取表格任意单元格 javascript如何动态删除表格某一行

    jsp页面表格布局Html代码 <body onload="show()"> <center> <input type="text" ...

  7. Unity3D研究院之动态修改烘培贴图的大小&脚本烘培场景

    Unity默认烘培场景以后每张烘培贴图的大小是1024.但是有可能你的场景比较简单,用1024会比较浪费.如下图所示,这是我的一个场景的烘培贴图,右上角一大部分完全是没有用到,但是它却占着空间.  有 ...

  8. lnmp下用phpize动态安装PHP模块/扩展(不需要重装PHP)

    安装前 安装前建议先执行 /usr/local/php/bin/php -m (此命令显示目前已经安装好的PHP模块)看一下,要安装的模块是否已安装.然后下载当前PHP版本的源码并解压. 本文以ima ...

  9. PHP 基础篇 - PHP 的 BC MATH 系列数学函数

    一.常见问题 用 PHP 做计算时经常会遇到精度带来的问题,下面来看两个常见的例子: 1. 运算比较 下面表达式输出的结果不是相等: <?php echo 2.01 - 0.01 == 2 ? ...

随机推荐

  1. STL之pair类型具体分析

    pair定义于头文件utility中.基本的作用是将两个数据组合成一个数据,两个数据能够是同一类型或者不同类型. pair类型提供的操作: pair<T1,T2> p1; pair< ...

  2. poj1270Following Orders(拓扑排序+dfs回溯)

    题目链接: 啊哈哈.点我点我 题意是: 第一列给出全部的字母数,第二列给出一些先后顺序. 然后按字典序最小的方式输出全部的可能性.. . 思路: 整体来说是拓扑排序.可是又非常多细节要考虑.首先要按字 ...

  3. remove-duplicates-from-sorted-array-ii——去除重复

    Follow up for "Remove Duplicates":What if duplicates are allowed at most twice? For exampl ...

  4. 好用的公共 DNS

    Google Public DNS: 8.8.8.8 8.8.4.4 2001:4860:4860::8888 2001:4860:4860::8844 OpenDNS: 208.67.222.222 ...

  5. Rom Modified [Galaxy 3 Tested]

    1,Virtualbox虚拟机设置-数据空间注意这里不要勾选那个自动挂载,不然后面mount总会提示mount.vbox.. invalid argument. 2,进入ubuntu中,在终端下输入 ...

  6. Android Activity间动画跳转

    本博文主要介绍activity间动画跳转的问题,在这里讲一下怎么设置全部activity的动画跳转和退出跳转.事实上有些软件已经这样做了.比方我们都比較熟悉的大众点评网. 以下我们通过一个实例来看一下 ...

  7. ARM和STM32的区别及ARM公司架构的发展

    ARM和STM32的区别及ARM公司架构的发展 转:https://www.cnblogs.com/kwdeblog/p/5260348.html ARM是英国的芯片设计公司,其最成功的莫过于32位嵌 ...

  8. Java系统中如何拆分同步和异步

    很多开发人员说,将应用程序切换到异步处理很复杂.因为他们有一个天然需要同步通信的Web应用程序.在这篇文章中,我想介绍一种方法来达到异步通信的目的:使用一些众所周知的库和工具来设计他们的系统. 下面的 ...

  9. scrapy之Logging使用

    #coding:utf-8 __author__ = 'similarface' ###################### ##Logging的使用 ###################### ...

  10. java中异或加密

    static String simple_xor(String base_data, String encrypt_key) throws UnsupportedEncodingException { ...