poj1700 Crossing River

Description

A group of N people wishes to go across a river with only one boat, which can at most carry two persons. Therefore some sort of shuttle arrangement must be arranged in order to row the boat back and forth so that all people may cross. Each person has a different rowing speed; the speed of a couple is determined by the speed of the slower one. Your job is to determine a strategy that minimizes the time for these people to get across.

Input

The first line of the input contains a single integer T (1 <= T <= 20), the number of test cases. Then T cases follow. The first line of each case contains N, and the second line contains N integers giving the time for each people to cross the river. Each case is preceded by a blank line. There won't be more than 1000 people and nobody takes more than 100 seconds to cross.

Output

For each test case, print a line containing the total number of seconds required for all the N people to cross the river.

Sample Input

1
4
1 2 5 10

Sample Output

17

AC Code

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <limits.h>
#include <queue>
#define inf 0x3f3f3f3f
using namespace std;



int main(int argc, char** argv) {
	int t,a[1010],n;
	cin>>t;
	while(t--){
		cin>>n;
		int i,sum=0;
		for(i=0;i<n;i++)
			cin>>a[i];
		sort(a,a+n);
		while(1)
		{
			if(n==1)
			{
				sum+=a[0];
				break;
			}
			if(n==2)
			{
				sum+=max(a[0],a[1]);
				break;
			}
			if(n==3)
			{
				sum+=(a[2]+a[0]+a[1]);
				break;
			}
			if(n>3)
			{
				sum+=min((2*a[1]+a[0]+a[n-1]),(a[n-1]+2*a[0]+a[n-2]));    
				n-=2;
			}
		}
		cout<<sum<<endl;
	}
	return 0;
}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章