百度笔试编程题:爬行的蚂蚁(c++)
2016-09-13 21:35
344 查看
题目:
有一个长m细木杆,有n只蚂蚁分别在木杆的任意位置。木杆很细,不能同时通过一只蚂蚁。开始时,蚂蚁的头朝左还是朝右是任意的,它们只会朝前走或调头,
但不会后退。当任意两只蚂蚁碰头时,两只蚂蚁会同时调头朝反方向走。假设蚂蚁们每秒钟可以走一厘米的距离。
编写程序,求所有蚂蚁都离开木杆 的最小时间和最大时间。
思路:
首先,讲一下思路:蚂蚁碰头后掉头,可以当作蚂蚁可以直接”穿过“对方,即蚂蚁碰头对蚂蚁运动没有影响。然后可以转换为每一只蚂蚁从初始位置直接到离开木杆的场景。求最短时间:以木杆中心为基准,左边的蚂蚁往左走,右边的蚂蚁往右走,这样子,左右两边的最短时间就是所求的最短时间。
求最长时间:以木杆中心为基准,左边的蚂蚁往右走,右边的蚂蚁往左走,这样子,时间就会最长
答案:
#include <iostream> using namespace std; int position[100]; int main(){ int T; scanf("%d",&T); while (T--) { int gan_length,ant_num,k; while(~scanf("%d%d",&gan_length,&ant_num)){ for(int i = 0; i < ant_num; ++i){ scanf("%d",&k); position[i] = k; } int speed = 1; //蚂蚁的速度 int max_time = 0; //最长时间 int min_time = 0; //最短时间 int temp_max = 0; int temp_min = 0; for(int i=0; i<ant_num; i++){ temp_max = 0; temp_min = 0; if (position[i] < gan_length / 2) //中点左边 { temp_max = (gan_length - position[i]) / speed; temp_min = position[i] / speed; } else //中点右边 { temp_max = position[i] / speed; temp_min = (gan_length - position[i]) / speed; } if (max_time < temp_max) max_time = temp_max; if (min_time < temp_min) min_time = temp_min; } cout<<min_time<<" "<<max_time<<endl; } } return 0; }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- 房产界已上市和IPO路上的难兄难弟:房天下与房多多
- 利用百度地图提供的API做的应用
- 搜狗百度360市值齐跌:搜索引擎们陷入集体焦虑?
- 百度20年:搜索帝国的崛起、式微与重生
- 小白观察:Google 开始清除百度旗下公司开发的 46 款应用程序
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- 百度全面恢复网站权重,流量暴涨中
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题