http://poj.org/problem?id=1700
Main topic:
There are n people to cross the river by boat, each person rowing a time a[i], each time a maximum of two people in a boat across the river. And the river crossing time for two people slow, seeking n the shortest time for individuals to cross the river.
Ideas:
Greedy.
For each crossing, there are two kinds of situations:
The quickest and slowest the past, and then the quickest to come back. In and times slow past. The quickest to come back int action1=a[i-1] + a[0] + a[i-2] +a[0];//the fastest and the next slow past, and then the quickest to come back, in the second slow and slowest past, times slow back int action2=a[1] +a[0] + a[i-1] +a[1];
You can do it every time you take the best.
#include <cstdio> #include <algorithm>using namespace Std;const int maxn=1024;int a[maxn];int main () {int T; scanf ("%d", &t), while ((t--)!=0) {int n;scanf ("%d", &n), for (int i=0;i<n;i++) scanf ("%d", &a[i]); sort (A, a+n) int i;int ans=0;for (i=n;i>=4;i-=2) {//the fastest and slowest in the past, then the quickest to come back, in and times slow the past, the fastest back int action1=a[i-1] + a[0] + a[i-2] +a[0];// The quickest and the slower the past, and then the quickest to come back, in the second slow and slowest past. Times slow back int action2=a[1] +a[0] + a[i-1] +a[1];ans=ans+ ((Action1 < Action2)? action1:action2);} if (i==3) ans+= a[0]+a[1]+a[2];if (i==2) ans+=a[1];if (i==1) ans+=a[0];p rintf ("%d\n", ans);} return 0;}
Import Java.util.arrays;import Java.util.scanner;public class Main {public static int[] A=new int[1024];p ublic static Voi D main (string[] args) {int T; Scanner in=new Scanner (system.in); T=in.nextint (), while ((t--)!=0) {int n=in.nextint (), for (int i=0;i<n;i++) a[i]=in.nextint (); Arrays.sort (a,0,n); int i;int ans=0;for (i=n;i>=4;i-=2) {//the fastest and slowest past, and then the quickest to come back, in and the Times slow over. The quickest to come back int action1=a[i-1] + a[0] + a[i-2] +a[0];//the fastest and the second slow past. Then the quickest to come back, at times slow and slowest past, times slow back int action2=a[1] +a[0] + a[i-1] +a[1];ans=ans+ ((Action1 < Action2)?Action1:action2);} if (i==3) ans+= a[0]+a[1]+a[2];if (i==2) ans+=a[1];if (i==1) ans+=a[0]; System.out.println (ANS);}}
POJ 1700 Crossing River C++/java