盲人过独木桥
来源:互联网 发布:1990人口普查数据 编辑:程序博客网 时间:2024/05/02 00:34
同学发来的题目,让帮忙解决。一开始拿到这个题目,感觉无从下手(新手懵逼),感觉也比较麻烦。等脑子清醒后,再想这个题目,其实也不难,只要一个清晰的思路就可以迎刃而解。在此记录下,方便回忆复习。
源代码程序:
#include <iostream>using namespace std;#define MAX_PERSON_NUM 50 //最多人数#define begin 0 //独木桥 头#define end 100 //独木桥 尾class Person{public: Person();public: int location; //位置 int patient_flag; //患病标志 int left_brige_flag;//离开独木桥标志};//初始化(构造函数)Person::Person(){ this->location = 0; this->patient_flag = 0; this->left_brige_flag = 0;}int main(){ int i = 0,j = 0; int patient_num = 0; //患病人数 int end_flag = 0; //结束标志 int left_brige_num = 0; //离开独木桥的人数 int person_num = 0; //输入的盲人数 Person Parr[MAX_PERSON_NUM]; //测试案例 /*Parr[1].location = -10; Parr[1].patient_flag = 1; Parr[2].location = 8; Parr[3].location = -20; Parr[4].location = 12; Parr[5].location = 25;*/ cout<<"输入盲人数量:"; cin>>person_num; cout<<"输入一行("<<person_num<<"个)"<<"用空格隔开的整数(-100 —— 100):"<<endl; //保存每个盲人的属性 for ( i = 1; i < person_num; i++) { cin>>Parr[i].location;//每个人的位置 if (i == 1) { Parr[1].patient_flag = 1;//第一个患病 } } while (end_flag == 0) { //1. 所有盲人 向前走一步 rate = 1m/s for ( i = 1; i < person_num; i++) { if (Parr[i].left_brige_flag == 0) { Parr[i].location++; } } //2. 是否相遇、患病 for ( i = 1; i < person_num; i++) { for ( j = i+1; j < person_num; j++) { if (Parr[i].left_brige_flag == 1 || Parr[j].left_brige_flag == 1) { continue; } if (abs(Parr[i].location) == abs(Parr[j].location))//相遇 { Parr[i].location = 0 - Parr[i].location;//反向 Parr[j].location = 0 - Parr[j].location; if ((Parr[i].patient_flag == 1) || (Parr[j].patient_flag == 1)) { Parr[i].patient_flag = 1;//患病 Parr[j].patient_flag = 1; } } } } //3. 到达起点或者终点 for ( i = 1; i < person_num; i++) { if ((Parr[i].location == begin) || (Parr[i].location == end)) { Parr[i].left_brige_flag = 1; } } left_brige_num = 0; //4. 结束条件 for ( i = 1; i < person_num; i++) { if (Parr[i].left_brige_flag == 1) { left_brige_num++; } } if (left_brige_num == person_num - 1) { end_flag = 1; } } //计算总的患病人数 for ( i = 1; i < person_num; i++) { if (Parr[i].patient_flag == 1) { patient_num++; } } cout<<endl; cout<<"patient_num:"<<patient_num<<endl;//输出患病人数 cout<<endl; system("pause"); return 0;}
这道题目用C++来写还是比较简单的,正好可以利用面向对象的class。用C写也可以,需要创建一个PERSON的结构体,或者数组来解决,不过就不如C++容易理解和编写代码。
代码有可以优化的地方,也没有添加输入数据异常的判断。只是一个思路的实现。
0 0
- 盲人过独木桥
- 独木桥
- 独木桥
- 独木桥
- 独木桥
- 盲人靠感觉过马路, 轻松走过障碍物,试验的科学家也同样称奇
- P1007 独木桥
- JZOJ4829. 独木桥
- 【u229】独木桥
- P1007 独木桥
- P1007 独木桥
- P1007_独木桥
- P1007独木桥
- 盲人国度
- 从未见过如此可笑的白领标准_独木桥的博客_雅虎博客_雅虎空间
- Google 盲人科学家推出盲人手机软件
- 独木桥的走法
- 【模拟\贪心】独木桥
- 2066 一个人的旅行
- plat_led驱动总结
- Python与人工神经网络(11)——为什么深度神经网络很难训练
- 11道Python基本面试题|深入解答
- 服务器向手机端推送消息理论
- 盲人过独木桥
- UITableView刷新一行、一个区
- Java面试准备九:Java的接口和抽象类
- Node.js学习笔记(1)
- 登录MYSQL时候报错, 报错信息: ERROR 1049 (42000): Unknown database 'xxxxxx'
- NB-IoT和LoRa的一些终端无线射频芯片公司
- linux上jdk的安装步骤与注意事项
- 热修复Tinker和多渠道打包Walle
- 概率编程简介