Main topic
In one night there are n people across the river, they have a flashlight, need to have a flashlight to cross the river, each time up to two people at the same time across the river, each time the river is equal to the speed of the slowest person's river crossing time, so that everyone across the river, spend the least amount of time?
Analysis
If only one person crosses the river, the total time to cross the river is the time when the man crosses the river. If it is two people crossing the river, then the total time for the river is slower than the person crossing the river time. If it is three people across the river, it takes time to a+b+c. When the number is equal to 4 o'clock, we let two slowest people cross the river each time, assuming that A and B represent the fastest and second fastest people, the speed of a,b,c and D is the slowest and the second slowest, the speed is c,d. The first strategy is to let A and B cross the river, a to return, C and D to cross the river, B to return, the time spent is 2*b+a+c. The second strategy is to let A and C cross the river, a returns, A and D cross the river, a returns, the time is spent 2*a+c+d. Compare the time spent on two strategies, and which time it takes to choose which strategy.
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#define MAXN 1005
using namespace Std;
int a[maxn],q[2][maxn*2];
int m,n;
int Solve ()
{
Int total=0,i;
M=-1;
for (i=n-1; i>=3; i-=2)
{
int t1=2*a[0]+a[i-1]+a[i];
int t2=2*a[1]+a[0]+a[i];
if (t1<t2)
{ br> m++;
Q[0][m]=a[0];
Q[1][m]=a[i];
m++;
Q[0][m]=a[0];
m++;
Q[0][m]=a[0];
Q[1][m]=a[i-1];
m++;
Q[0][m]=a[0];
Total+=t1;
}
Else
{
m++;
Q[0][m]=a[0];
Q[1][m]=a[1];
m++;
Q[0][m]=a[0];
m++;
Q[0][m]=a[i-1 ];
Q[1][m]=a[i];
m++;
Q[0][m]=a[1];
Total+=t2;
}
}
if (i==2)
{
TOTAL+=A[0]+A[1]+A[2];
m++;
Q[0][M]=A[0];
Q[1][M]=A[2];
m++;
Q[0][M]=A[0];
m++;
Q[0][M]=A[0];
Q[1][M]=A[1];
}
else if (i==1)
{
TOTAL+=A[1];
m++;
Q[0][M]=A[0];
Q[1][M]=A[1];
}
Else
{
TOTAL+=A[0];
m++;
Q[0][M]=A[0];
}
return total;
}
int main (void)
{
int t;
scanf ("%d", &t);
while (t--)
{
scanf ("%d", &n);
for (int i=0; i<n; i++)
scanf ("%d", &a[i]);
Sort (a,a+n);
memset (q,0,sizeof (q));
printf ("%d\n", Solve ());
for (int i=0; i<=m; i++)
{
printf ("%d", q[0][i]);
if (Q[1][i])
printf ("%d", q[1][i]);
printf ("\ n");
}
if (t) printf ("\ n");
}
return 0;
}
UVa 10037-bridge