同学发来的题目,让帮忙解决。一开始拿到这个题目,感觉无从下手(新手懵逼),感觉也比较麻烦。等脑子清醒后,再想这个题目,其实也不难,只要一个清晰的思路就可以迎刃而解。在此记录下,方便回忆复习。
源代码程序:
#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++容易理解和编写代码。
代码有可以优化的地方,也没有添加输入数据异常的判断。只是一个思路的实现。