poj1700(ny47)(過河問題)(貪心)

poj1700(ny47)(過河問題)(貪心)
Crossing River
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 12680   Accepted: 4828

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
注:第一組樣例:

(1)先過x[1]、x[2],然後x[1]再回去。(2)再過x[3],x[4],x[2]回去。(3)x[1]、x[2]再過

當有多個人時即:.n>=4時,每次取四個人一組,先把x[1]、x[2]固定,每次先送四人組中的後2個人。

共有兩種方法:

如;四個人時:

一、(1)  x[1]、x[4],過河

        (2)  x[1],回去

       (3)x[1]、x[3],過河

       (4)x[1],回去

        (5)x[1]、x[2],過河

二、

(1)  x[1]、x[2],過河

        (2)  x[1],回去

       (3)x[3]、x[4],過河

       (4)x[2],回去

        (5)x[1]、x[2],過河

上述兩種方法;在第五步時是一樣的,所以只需比較前四步耗時即可。當第二種方法之所以比第一種方法優時,主要是後面兩個人的過河時間比較長,

當後面兩個人過河時間較短時,第二種方法沒有第一種方法優。

My  solution:

/*2016.3.26*/

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
long  long  x[1100],h,ans,pt;
long  long solve(long  long h)
{
	
	long  long m1,m2,i,j,k;
	m1=2*x[2]+x[1]+x[h];//第一種方法送過去後面兩人 
	m2=2*x[1]+x[h-1]+x[h];//第二種方法送過去後面兩人 
	if(m1<m2)              //第一種方法與第二種方法送過去前兩人用時一樣即:x[1]與x[2]一起過河 
	{
	  return m1;
	}
	else
	return 0;
}
int main()
{
	long  long m,t,n,i,j,k;
	long  long t1,t2;
	scanf("%lld",&t);
	while(t--)
	{
		pt=0;
		scanf("%lld",&n);
		h=n;
		ans=0;
		t1=0;t2=0;
		for(i=1;i<=n;i++)
		scanf("%lld",&x[i]);
		sort(x+1,x+n+1);
		while(1<(h-2))
		{
			m=solve(h);
			if(m==0)//當第二種方法比第一種省時,再往下繼續過河時,第二種方法必定一直比第一種 方法優 
			          //因爲再往下繼續過河時,四人組中後面兩個人的用時越來越短,第一種方法的優勢就不存在了 
		    {         //所以直接結束循環判斷,剩下的人全部用第二種方法過河 
		      break;
			}
			t1+=m;
			h=h-2;
		}
		if(h>1)//當h不足四人且多於1人或者第二種方法比第一種方法更省時,直接用第二種方法求解剩下用時 
		t1+=(h-2)*x[1];
		else//少考慮只有一個人的情況 
		t1=x[1];
		for(i=2;i<=h;i++)
		t1+=x[i];
	     printf("%lld\n",t1);
	}
	return 0;
}

發佈了144 篇原創文章 · 獲贊 10 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章