Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 4143 | Accepted: 1703 |
Description
A group of N travelers (1 ≤ N ≤ 50) has approached an old and shabby bridge and wishes to cross the river as soon as possible. However, there can be no more than two persons on the bridge at a time. Besides it's necessary to light the way with a torch for safe crossing but the group has only one torch.
Each traveler needs ti seconds to cross the river on the bridge; i=1, ... , N (ti are integers from 1 to 100). If two travelers are crossing together their crossing time is the time of the slowest traveler.
The task is to determine minimal crossing time for the whole group.
Input
The input consists of two lines: the first line contains the value of N and the second one contains the values of ti (separated by one or several spaces).
Output
The output contains one line with the result.
Sample Input
4 6 7 6 5
Sample Output
29
Source
#include<iostream> #include<stdio.h> #include<string.h> #include<algorithm> using namespace std; int a[51],dp[51]; int main(){ int n; while(scanf("%d",&n)!=EOF){ for(int i=1;i<=n;i++) scanf("%d",&a[i]); memset(dp,0,sizeof(dp)); sort(a+1,a+n+1); dp[1] = a[1]; dp[2] = a[2]; for(int i=3;i<=n;i++){ dp[i] = min(dp[i-1]+a[i]+a[1],dp[i-2]+a[i]+2*a[2]+a[1]); } printf("%d ",dp[n]); } }
poj 1700(java大数据版):注意处理n=1的特殊情况
import java.math.BigInteger; import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc =new Scanner(System.in); int tcase= sc.nextInt(); while(tcase-->0){ int n =sc.nextInt(); if(n==1) { int v = sc.nextInt(); System.out.println(v); continue; } BigInteger [] a = new BigInteger[n+1]; BigInteger [] dp = new BigInteger[n+1]; for(int i=1;i<=n;i++){ int v = sc.nextInt(); a[i] = BigInteger.valueOf(v); } Arrays.sort(a,1,n+1); //for(int i=1;i<=n;i++) System.out.println(a[i]); dp[1] = a[1]; dp[2] = a[2]; for(int i=3;i<=n;i++){ BigInteger c1 = dp[i-1].add(a[i]).add(a[1]); BigInteger c2 = dp[i-2].add(a[1]).add(a[2].multiply(BigInteger.valueOf(2))).add(a[i]); if(c1.compareTo(c2)>0) dp[i] = c2; else dp[i] = c1; } System.out.println(dp[n]); } } }