可以看到,买票问题是一个典型的动态规划问题,为什么这样说?因为当前最短时间依赖于之前的买票决策。
确定了是动态规划问题后,我们的主要任务就是寻找状态转移方程了。
以下面的例子做个说明
int[] a={3,5,7,6};
int[] b={6,11,13};
在解决这个问题时,我们实际上是在求在数组a中,到从位置0到位置ptr处,我们累计的最小值
例如,当ptr=0时,显然当前最短时间时间
dp[ptr]=a[0]
当ptr=1时,当前最短时间为
dp[ptr]=min(a[0]+a[1],b[0])
显然,当ptr=2时,最短时间为min(dp[ptr-1]+a[ptr],dp[ptr-2]+b[ptr-1])。
dp[ptr]=min(dp[ptr-1]+a[ptr],dp[ptr-2]+b[ptr-1])
后面的都可以继续递推
/**
* @param a 单独购买的时间
* @param b 两个人一起买的时间
* @return
*/
public static int timeToClose(int[] a,int[] b){
if (a.length==0||a.length==1){
return a.length==0?0:a[0];
}
int[] dp=new int[a.length];
dp[0]=a[0];
dp[1]=Math.min(b[0],a[0]+a[1]);
int ptr=2;
while (ptr<a.length){
//a[ptr]表示单独购买的花费时间,dp[ptr-1]表示从第0个人到第ptr-1个人总共花费的最小时间
//b[ptr-1]表示第ptr个人和第ptr-1个人一起花费的时间,dp[ptr-2]表示从第0个人到第ptr-2个人总共花费的最小时间
dp[ptr++]=Math.min(a[ptr]+dp[ptr-1],b[ptr-1]+dp[ptr-2]);
}
return dp[dp.length-1];
}
完整java 代码
package wangyi2021;
import java.util.Scanner;
public class second {
static int t, n, res;
public static int timeToClose(int[] a,int[] b){
if (a.length==0||a.length==1){
return a.length==0?0:a[0];
}
int[] dp=new int[a.length];
dp[0]=a[0];
dp[1]=Math.min(b[0],a[0]+a[1]);
int ptr=2;
while (ptr<a.length){
//a[ptr]表示单独购买的花费时间,dp[ptr-1]表示从第0个人到第ptr-1个人总共花费的最小时间
//b[ptr-1]表示第ptr个人和第ptr-1个人一起花费的时间,dp[ptr-2]表示从第0个人到第ptr-2个人总共花费的最小时间
dp[ptr++]=Math.min(a[ptr]+dp[ptr-1],b[ptr-1]+dp[ptr-2]);
}
return dp[dp.length-1];
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
t = sc.nextInt();
while(t-- != 0){
n = sc.nextInt();
int[] a;int[] b;
a = new int[n];
b = new int[n-1];
res = 0;
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
//res += a[i];
}
for (int i = 0; i < n-1; i++) {
b[i] = sc.nextInt();
//res += a[i];
}
//dfs(0, 0, 0, 0);
//System.out.println(timeToClose(a, b));
int result=timeToClose(a, b);
int h = 8, m = 0, s = 0;
s = (s+result)%60;
m = (m+result/60)%60;
h = (h+result/3600)%24;
if (h < 12 || h == 12 && s == 0 && h == 0)
System.out.print(String.format("%02d:%02d:%02d am\n", h, m, s));
else System.out.print(String.format("%02d:%02d:%02d pm\n", h-12, m, s));
}
}
}