Kattis -Safe Passage(撑伞问题)

Safe Passage

/problems/safepassage/file/statement/en/img-0001.png
Photo by Ian Burt

A group of friends snuck away from their school campus, but now they must return from the main campus gate to their dorm while remaining undetected by the many teachers who patrol the campus. Fortunately, they have an invisibility cloak, but it is only large enough to cover two people at a time. They will take turns as individuals or pairs traveling across campus under the cloak (and by necessity, returning the cloak to the gate if others remain). Each student has a maximum pace at which he or she is able to travel, yet if a pair of students are walking under the cloak together, they will have to travel at the pace of the slower of the two. Their goal is to have everyone back at the dorm as quickly as possible.

As an example, assume that there are four people in the group, with person A able to make the trip in $1$ minute, person B able to travel in $2$ minutes, person C able to travel in $7$ minutes, and person D able to travel in $10$ minutes. It is possible to get everyone to the dorm in $17$ minutes with the following plan:

– A and B go from the gate to the dorm together

(taking $2$ minutes)

– A returns with the cloak to the gate

(taking $1$ minute)

– C and D go from the gate to the dorm together

(taking $10$ minutes)

– B returns with the cloak to the gate

(taking $2$ minutes)

– A and B go from the gate to the dorm together

(taking $2$ minutes)

Input

The input is a single line beginning with an integer, $2 leq N leq 15$. Following that are $N$ positive integers that respectively represent the minimum time in which each person is able to cross the campus if alone; these times are measured in minutes, with each being at most $5\, 000$. (It is a very large campus!)

Output

Output the minimum possible time it takes to get the entire group from the gate to the dorm.

Sample Input 1Sample Output 1
2 15 5
15
Sample Input 2Sample Output 2
4 1 2 7 10
17
Sample Input 3Sample Output 3
5 12 1 3 8 6
29

题意

这是一道很经典的撑伞问题吧,有n个人,每个人带一个时间,为这个人走起点到终点的时间,然后斗篷每次只能最多两个人撑,斗篷只有一件,过去的时候时间算慢那个人的,过去了需要有人送回来,

求所有人都到终点的最少时间

思路

按照样例解释,我们很容易想到,第一次肯定是最快的两个人先过去,然后,每次的选择都有两种策略,最快那个回来,把最慢的和次慢依次送过去,或者次快的回来,让最慢的和次慢的过去,我们要取这两种策略中最少时间的,最后剩下两个人的时候,就是最快的回来,第二第三快的过去,第二快的回来。

代码

#include<bits/stdc++.h>
using namespace std;
int main() {
    int n;
    int a[20];
    scanf("%d", &n);
    for(int i = 0; i < n; i++)
        scanf("%d", &a[i]);
    sort(a, a + n);
    int i, cnt = 0;
    for(i = n - 1; i > 2; i -= 2)
        cnt += min(a[0] + a[1] + a[1] + a[i], a[0] + a[0] + a[i] + a[i - 1]);
    if(i == 2)
        cnt += a[0] + a[1] + a[2];
    else if(i == 1)
        cnt += a[1];
    else
        cnt += a[0];
    printf("%d
", cnt);
}
原文地址:https://www.cnblogs.com/zhien-aa/p/6295829.html