一道面試題轉化爲編程題——過橋最短時間花費

原面試題

1、四個人。

2、這四個人分別過橋的時間爲1分鐘、2分鐘、5分鐘、10分鐘。

3、當時正是晚上,他們只有一個手電筒,只能在擁有手電筒的情況下過橋。

4、橋最多隻能容納兩個人同時過橋。

那麼問題來了:這四個人均到達對岸的最小時間?


後來覺得這題挺有意思的,就想到了如果是N個人,每個人過橋時間都不同,那麼所有人到達對岸的最小時間是多少呢?

接着我就出了這麼一道題給學弟們做。


問題描述
NBUT的ACMers今天興致勃勃的去爬山,但是由於玩的太興奮,直到天黑也沒到山腳下。
這時,前面突然出現一座橋,但是他們只有1個手電筒,而且那座橋只能容納兩個人同時過去,超過兩個人的話,橋就會塌了。
而且每個人過橋所用的時間也不相同。如果沒有手電筒,摸着黑去過橋也會不小心掉下去的。所以當兩個人拿着手電筒到橋的另一端時,必須要有一個人拿着手電筒回來。
因爲要急着趕回家,所以他們需要儘可能少的時間到達對岸,你能幫他們想想辦法嗎?

輸入
第一行包含一個正整數N(1 <= N <= 1000)表示ACMers的人數。
接下來一行有N個數,每個數代表第Ai個人過橋所花的整數時間Ti(1 <= Ti <= 1000)。

輸出
輸出一行,表示最短過橋時間。

樣例輸入
4
1 2 5 10

樣例輸出
17


代碼

#include <set>
#include <map>
#include <list>
#include <stack>
#include <queue>
#include <cmath>
#include <cstdio>
#include <vector>
#include <string>
#include <iomanip>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;

#define LL64 __int64
#define LL long long
#define N 1010
#define M 210

int a[N];

int main()
{
	int n;
	
	//freopen("data.in", "r", stdin);
	//freopen("data.out", "w", stdout);
	while (~scanf("%d", &n))
	{
		for (int i = 0; i < n; i++)
		{
			scanf("%d", &a[i]);
		}
		if (n == 1)
		{
			printf("%d\n", a[0]);
			continue;
		}
		if (n == 2)
		{
			printf("%d\n", max(a[0], a[1]));
			continue;
		}
		if (n == 3)
		{
			printf("%d\n", a[0] + a[1] + a[2]);
			continue;
		}
		sort(a, a + n);
		int s = 0;
		for (int i = n - 1; i > 0; i -= 2)
		{
			if (i == 2) s += a[i] + a[i - 1] + a[i - 2];
			else if (i == 1) s += max(a[i], a[i - 1]);
			else if (a[i - 1] + a[0] > a[1] * 2) s += a[1] * 2 + a[i] + a[0];
			else s += a[0] + a[i - 1] + a[i] + a[0];
		}
		printf("%d\n", s);
	}
	
	return 0;
}


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