组合题5 个小题
已作答 0 / 5
完善程序: (过河问题) 在一个月黑风高的夜晚,有一群人在河的右岸,想通过唯一的一根独木桥走到河的左岸。在这伸手不见五指的黑夜里,过桥时必须借助灯光来照明,很不幸的是,他们只有一盏灯。另外,独木桥上最多承受两个人同时经过,否则将会坍塌。每个人单独过桥都需要一定的时间,不同的人需要的时间可能不同。两个人一起过桥时,由于只有一盏灯,所以需要的时间是较慢的那个人单独过桥时所花的时间。现输入 n(2≤n<100 和这 n 个人单独过桥时需要的时间,请计算总共最少需要多少时间,他们才能全部到达河的左岸。
例如,有 3 个人甲、乙、丙,他们单独过桥的时间分别为 1,2,4,则总共最少需要的时间为 7。具体方法是:甲、乙一起过桥到河的左岸,甲单独回到河的右岸将灯带回,然后甲、丙再一起过桥到河的左岸,总时间为 2+1+4=7。
1#include <iostream>2using namespace std;3 4const int SIZE = 100;5const int INFINITY = 10000;6const bool LEFT = true;7const bool RIGHT = false;8const bool LEFT_TO_RIGHT = true;9const bool RIGHT_TO_LEFT = false;10 11int n, hour[SIZE];12bool pos[SIZE];13 14int max(int a, int b)15{16 if (a > b)17 return a;18 else19 return b;20}21 22int go(bool stage)23{24 int i, j, num, tmp, ans;25 if (stage == RIGHT_TO_LEFT) {26 num = 0;27 ans = 0;28 for (i = 1; i <= n; i++)29 if (pos[i] == RIGHT) {30 num++;31 if (hour[i] > ans)32 ans = hour[i];33 }34 if ([ ① ])35 return ans;36 ans = INFINITY;37 for (i = 1; i <= n - 1; i++)38 if (pos[i] == RIGHT)39 for (j = i + 1; j <= n; j++)40 if (pos[j] == RIGHT) {41 pos[i] = LEFT;42 pos[j] = LEFT;43 tmp = max(hour[i], hour[j]) +[ ② ];44 if (tmp < ans)45 ans = tmp;46 pos[i] = RIGHT;47 pos[j] = RIGHT;48 }49 return ans;50 }51 if (stage == LEFT_TO_RIGHT) {52 ans = INFINITY;53 for (i = 1; i <= n; i++)54 if ([ ③ ]) {55 pos[i] = RIGHT;56 tmp =[ ④ ];57 if (tmp < ans)58 ans = tmp;59 [ ⑤ ];60 }61 return ans;62 }63 return 0;64}65 66int main()67{68 int i;69 70 cin>>n;71 for (i = 1; i <=n; i++) {72 cin>>hour[i];73 pos[i] = RIGHT;74 }75 cout<<go(RIGHT_TO_LEFT)<<endl;76 return 0;77}⑤处应填( )