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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章