您的位置:首页 > 其它

过桥问题【经典笔试问题】

2012-11-13 20:36 204 查看
#include <assert.h>

#include <stdio.h>
#include <stdlib.h>
int CrossBridge(int n, int *p);
int cmp(const void*p1, const void *p2)
{
return *(int*)p1-*(int*)p2;
}
int main()
{

int *p;
int n;
printf("enter the group size: ");
scanf("%d",&n);
p=new int
;
int i;
for (i=0;i<n;i++)
{
scanf("%d",p+i);
}

qsort(p,n,sizeof(int),cmp);
printf("time: %d\n",CrossBridge(n,p));

delete []p;
return 0;
}

int CrossBridge(int n, int *p)
{

assert(n>0 && NULL != p);

int ti=0;
if (n==1)
{
printf("A-->B: %d\n", p[0]);
ti=p[0];
return ti;
}
else if (n==2)
{
printf("A-->B: %d, %d\n", p[0], p[1]);
ti=p[1];
return ti;
}
else if (n==3)
{
printf("A-->B: %d, %d\n", p[0],p[1]);
printf("B-->A: %d\n", p[0]);
printf("A-->B: %d, %d\n", p[0],p[2]);
ti=p[1]+p[0]+p[2];
return ti;
}
else
{
if (p[0]+p[n-2] > p[1]*2)
{
printf("A-->B: %d, %d\n", p[0],p[1]);
printf("B-->A: %d\n", p[0]);
printf("A-->B: %d, %d\n", p[n-2],p[n-1]);
printf("B-->A: %d\n", p[1]);
return p[1]+p[0]+p[n-1]+p[1]+CrossBridge(n-2,p);

}else
{
printf("A-->B: %d, %d\n", p[0],p[n-1]);
printf("B-->A: %d\n", p[0]);
printf("A-->B: %d, %d\n", p[0],p[n-2]);
printf("B-->A: %d\n", p[0]);
return p[n-1]+p[n-2]+p[0]+p[0]+CrossBridge(n-2,p);

}
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: