在漆黑的夜里,n位旅行者来到了一座狭窄而且没有护栏的桥边。如果不借助手电筒的话,大家是无论如何也不敢过桥去的。不幸的是,他们一共只带了一只手电筒,而桥窄得只够让两个人同时过。如果各自单独过桥的话,每人所需要的时间分别是a1、a2、...an分钟;而如果两人同时过桥,所需要的时间就是走得比较慢的那个人单独行动时所需的时间。问题是,如何设计一个方案,让这些人尽快过桥。
Input
输入分2行
第一行是一个整数n(1<=n<=1000)
第二行是n个整数,分别表示这n个人单独过桥需要的时间
Output
输出2行:
第一行,他们过桥需要的总时间。
第二行,他们的走法。
input as:
8
1 2 3 6 8 12 9 4
output as:
time:
left right
(1 2 Cross) <----
(1 back) ---->
(9 12 Cross ) <----
(2 back) ---->
(1 2 Cross) <----
(1 back) ---->
(6 8 Cross) <----
……
求c语言过桥问题最后要输出走法的代码怎么写
答案:2 悬赏:70
解决时间 2021-03-04 00:30
- 提问者网友:猖狂醉薇
- 2021-03-03 07:45
最佳答案
- 二级知识专家网友:木子香沫兮
- 2021-03-03 08:03
#include
#include
typedef struct people
{
int index;
int time;
int wei;//0为没过河,1为过河
}PEO;
void paixu(PEO a[],int n)
{
int i, j;
PEO t;
for (i = 0; i
for (j = 0; j
if (a[j].time>a[j + 1].time)
{
t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
int main()
{
int n, total=0 ,i;
PEO *a;
scanf("%d", &n);
a = (int*)malloc(n*sizeof(PEO));
for (i = 0; i < n; i++)
{
scanf("%d", &(a[i].time));
a[i].index = i + 1;
a[i].wei = 0;
}
paixu(a, n);
for (;n>0;)
{
if (!a[0].wei&&!a[1].wei)
{
printf("(%d %d Cross) <----\n", a[0].index, a[1].index);
a[0].wei = 1; a[1].wei = 1; n = n - 2;
total += a[1].time;
}
else if (a[0].wei)
{
printf("(%d back) ---->\n", a[0].index);
a[0].wei = 0; n = n + 1;
total += a[0].time;
}
else if (n == 2)
{
printf("(%d %d Cross) <----\n", a[0].index, a[n].index);
total += a[n].time;
break;
}
else
{
printf("(%d %d Cross) <----\n", a[n-1].index, a[n].index);
printf("(%d back) ---->\n", a[1].index);
total += a[1].time + a[n].time;
a[1].wei = 0; n = n - 1;
}}
printf(" time:%d", total);
system("pause");
return 0;
}//先算时间的话我规律找不到(⊙﹏⊙)b
#include
typedef struct people
{
int index;
int time;
int wei;//0为没过河,1为过河
}PEO;
void paixu(PEO a[],int n)
{
int i, j;
PEO t;
for (i = 0; i
{
t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
int main()
{
int n, total=0 ,i;
PEO *a;
scanf("%d", &n);
a = (int*)malloc(n*sizeof(PEO));
for (i = 0; i < n; i++)
{
scanf("%d", &(a[i].time));
a[i].index = i + 1;
a[i].wei = 0;
}
paixu(a, n);
for (;n>0;)
{
if (!a[0].wei&&!a[1].wei)
{
printf("(%d %d Cross) <----\n", a[0].index, a[1].index);
a[0].wei = 1; a[1].wei = 1; n = n - 2;
total += a[1].time;
}
else if (a[0].wei)
{
printf("(%d back) ---->\n", a[0].index);
a[0].wei = 0; n = n + 1;
total += a[0].time;
}
else if (n == 2)
{
printf("(%d %d Cross) <----\n", a[0].index, a[n].index);
total += a[n].time;
break;
}
else
{
printf("(%d %d Cross) <----\n", a[n-1].index, a[n].index);
printf("(%d back) ---->\n", a[1].index);
total += a[1].time + a[n].time;
a[1].wei = 0; n = n - 1;
}}
printf(" time:%d", total);
system("pause");
return 0;
}//先算时间的话我规律找不到(⊙﹏⊙)b
全部回答
- 1楼网友:初心未变
- 2021-03-03 08:25
同问。。。
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯