1014 Waiting in Line

本文介绍了一个银行排队模拟问题,通过使用队列数组模拟窗口队伍,实现了顾客选择最短队列等待并计算其业务完成时间的功能。考虑到银行17:00关门的限制,对无法在该时间前完成交易的顾客输出'Sorry'。

Suppose a bank has N windows open for service. There is a yellow line in front of the windows which devides the waiting area into two parts. The rules for the customers to wait in line are:

  • The space inside the yellow line in front of each window is enough to
    contain a line with MMM customers. Hence when all the NNN lines are full,
    all the customers after (and including) the (NM+1)(NM+1)(NM+1)st one will have to
    wait in a line behind the yellow line.

  • Each customer will choose the shortest line to wait in when crossing the yellow line. If there are two or more lines with the same length, the customer will always choose the window with the smallest number.

  • CustomeriCustomer_iCustomeri​​ will take TiT_iTi​​ minutes to have his/her transaction processed.

  • The first NNN customers are assumed to be served at 8:00am.

Now given the processing time of each customer, you are supposed to tell the exact time at which a customer has his/her business done.

For example, suppose that a bank has 2 windows and each window may have 2 custmers waiting inside the yellow line. There are 5 customers waiting with transactions taking 1, 2, 6, 4 and 3 minutes, respectively. At 08:00 in the morning, customer​1​​ is served at window​1​​ while customer​2​​ is served at window​2​​. Customer​3​​ will wait in front of window​1​​ and customer​4​​ will wait in front of window​2​​. Customer​5​​ will wait behind the yellow line.

At 08:01, customer​1​​ is done and customer​5​​ enters the line in front of window​1​​ since that line seems shorter now. Customer​2​​ will leave at 08:02, customer​4​​ at 08:06, customer​3​​ at 08:07, and finally customer​5​​ at 08:10.
Input Specification:

Each input file contains one test case. Each case starts with a line containing 4 positive integers: N(≤20N (≤20N(20, number of windows), M(≤10M (≤10M(10, the maximum capacity of each line inside the yellow line), K(≤1000K (≤1000K(1000, number of customers), and Q(≤1000Q (≤1000Q(1000, number of customer queries).

The next line contains KKK positive integers, which are the processing time of the KKK customers.

The last line contains Q positive integers, which represent the customers who are asking about the time they can have their transactions done. The customers are numbered from 1 to K.

Output Specification:

For each of the Q customers, print in one line the time at which his/her transaction is finished, in the format HH:MM where HH is in [08, 17] and MM is in [00,59][00, 59][00,59]. Note that since the bank is closed everyday after 17:00, for those customers who cannot be served before 17:00, you must output Sorry instead.
Sample Input:

2 2 7 5
1 2 6 4 3 534 2
3 4 5 6 7

Sample Output:

08:07
08:06
08:10
17:00
Sorry

题解:

模拟题,可以使用一个队列数组来模拟窗口队伍,需要注意的是:如果服务在17:00之前开始,即使超时,仍然是允许的,而不是输出Sorry,以及对于这类场景模拟题,一般是不会太卡时间,所以只需按照题目描述一步一步的实现,最后再进行剪枝即可;
说明一下,对于< queue >中元素的修改,并不会影响到元素本身的值;


#include <iostream>
#include <queue>
#include <iomanip>
using namespace std;
#define MAXLINE 20
#define MAXTIME 0x3FFFFFFF

struct Customer{
    int id, processing;
    int time = MAXTIME;		// 完成时间
};
int N,M,K,Q;
queue<Customer> q[20];

int FindShortest(){		// 寻找最短队列
    int MinQ = MAXLINE, line = 0;
    for(int i=0;i<N;i++){
        if(q[i].size() < MinQ){
            MinQ = q[i].size();
            line = i;
        }
    }
    return line;
}

int FindQuickest(){		// 寻找下一个最快完成的队列
    int MinT = MAXTIME, line = 0;
    for(int i=0;i<N;i++){
        if(q[i].front().processing < MinT && !q[i].empty()){
            MinT = q[i].front().processing;
            line = i;
        }
    }
    return line;
}

int main()
{
    int time = 0;
    Customer C[1005];
    cin>>N>>M>>K>>Q;
    for(int i=1;i<=K;i++){
        C[i].id = i;
        cin>>C[i].processing;
    }

    int cont_in = 0, index = 1;
    int id, processing, line;
    do{
        while(cont_in < N*M && index <= K ){
            q[FindShortest()].push(C[index++]);
            cont_in++;
        }

        line = FindQuickest();
        id = q[line].front().id;
        processing = q[line].front().processing;
        for(int i=0;i<N;i++){
            if(!q[i].empty())
                q[i].front().processing -= processing;
        }
        q[line].pop();
        time += processing;
        C[id].time = time;
        cont_in--;
    }while(cont_in > 0);

    int hour,minute;
    for(int i=0;i<Q;i++){
        cin>>id;
        if(C[id].time - C[id].processing < 540){
            hour = C[id].time/60;
            minute = C[id].time%60;
            cout<<setw(2)<<setfill('0')<<hour+8;
            cout<<":";
            cout<<setw(2)<<setfill('0')<<minute<<endl;
        }
        else
            cout<<"Sorry\n";          // 如果服务在17:00之前开始,即使超时,仍然是允许的,而不是输出Sorry
    }
}
先展示下效果 https://pan.quark.cn/s/a4b39357ea24 遗传算法 - 简书 遗传算法的理论是根据达尔文进化论而设计出来的算法: 人类是朝着好的方向(最优解)进化,进化过程中,会自动选择优良基因,淘汰劣等基因。 遗传算法(英语:genetic algorithm (GA) )是计算数学中用于解决最佳化的搜索算法,是进化算法的一种。 进化算法最初是借鉴了进化生物学中的一些现象而发展起来的,这些现象包括遗传、突变、自然选择、杂交等。 搜索算法的共同特征为: 首先组成一组候选解 依据某些适应性条件测算这些候选解的适应度 根据适应度保留某些候选解,放弃其他候选解 对保留的候选解进行某些操作,生成新的候选解 遗传算法流程 遗传算法的一般步骤 my_fitness函数 评估每条染色体所对应个体的适应度 升序排列适应度评估值,选出 前 parent_number 个 个体作为 待选 parent 种群(适应度函数的值越小越好) 从 待选 parent 种群 中随机选择 2 个个体作为父方和母方。 抽取父母双方的染色体,进行交叉,产生 2 个子代。 (交叉概率) 对子代(parent + 生成的 child)的染色体进行变异。 (变异概率) 重复3,4,5步骤,直到新种群(parentnumber + childnumber)的产生。 循环以上步骤直至找到满意的解。 名词解释 交叉概率:两个个体进行交配的概率。 例如,交配概率为0.8,则80%的“夫妻”会生育后代。 变异概率:所有的基因中发生变异的占总体的比例。 GA函数 适应度函数 适应度函数由解决的问题决定。 举一个平方和的例子。 简单的平方和问题 求函数的最小值,其中每个变量的取值区间都是 [-1, ...
<think> 我们正在分析一段Python代码:`while ser.in_waiting > 0: line = ser.readline().decode().strip()` 这段代码通常用于串口通信(通过pyserial库),用于读取串口接收缓冲区中的数据。 让我们逐步分解: 1. `ser.in_waiting`: - 这是pyserial库中Serial对象的一个属性。 - 它返回当前串口接收缓冲区中等待读取的字节数(整数)。 - 如果返回值大于0,表示有数据可读。 2. `while ser.in_waiting > 0:`: - 这是一个循环条件,只要串口接收缓冲区中有数据(字节数大于0),循环就会继续执行。 - 循环会一直读取数据,直到缓冲区为空(`in_waiting`为0)。 3. `ser.readline()`: - 这是Serial对象的一个方法,用于从串口读取一行数据。 - 它会一直读取,直到遇到换行符(如`\n`)或者达到设定的超时时间。 - 返回的是字节序列(bytes类型),例如:`b'hello\r\n'`。 4. `.decode()`: - 将`readline()`读取的字节序列(bytes)解码为字符串(string)。 - 默认使用UTF-8编码,也可以指定其他编码,例如:`.decode('ascii')`。 5. `.strip()`: - 去除字符串首尾的空白字符(包括换行符`\n`、回车符`\r`、空格等)。 - 例如:将字符串`"hello\r\n"`处理成`"hello"`。 因此,整行代码的含义是: 当串口接收缓冲区中有数据时,循环读取每一行数据(以换行符为分隔),将读取的字节数据转换为字符串,并去除首尾的空白字符,然后将结果赋值给变量`line`。 注意:在循环中,每次读取一行,然后变量`line`会被重新赋值。因此,如果缓冲区中有多行数据,循环会逐行读取,但最后变量`line`只保留最后读取的一行。如果需要处理每一行,应该在循环体内对每一行进行处理(例如,添加到列表中)。 示例:假设串口接收缓冲区中有三行数据:"first line\nsecond line\nthird line\n" 循环将执行三次: 第一次:line = "first line" 第二次:line = "second line" 第三次:line = "third line" 循环结束后,line变量中存储的是"third line"。 所以,通常我们会这样写来处理每一行: ``` lines = [] # 创建一个空列表存储每一行 while ser.in_waiting > 0: line = ser.readline().decode().strip() lines.append(line) # 将每一行添加到列表中 ``` 或者直接在循环体内处理每一行(如打印、解析等)。 另外,需要注意的是,串口通信是流式传输,可能不会一次就收到完整的一行,也可能一次收到多行。因此,使用`readline()`可以按行读取,但要注意超时设置(在打开串口时设置timeout参数),否则可能会一直等待换行符。 总结:这段代码的作用是连续读取串口缓冲区中的所有行(直到缓冲区为空),并将每一行转换为去除首尾空格的字符串。 相关问题: 1. 如何设置串口的超时时间? 2. 如果数据不是以换行符结尾,`readline()`会怎样? 3. 如何避免在读取过程中丢失数据? 4. 除了`readline()`,还有哪些读取串口数据的方法? </think> ### Python代码解析:`while ser.in_waiting > 0: line = ser.readline().decode().strip()` 这段代码是**串口通信中的典型数据读取逻辑**,主要用于处理来自串口设备(如传感器、单片机等)的连续数据流。以下是逐层解析: --- #### 1. **组件拆解** | 代码片段 | 功能说明 | |---------------------------|--------------------------------------------------------------------------| | `ser` | 串口对象(通过 `pyserial` 库创建)[^1] | | `ser.in_waiting` | 返回接收缓冲区中的字节数(整数) | | `ser.in_waiting > 0` | 判断缓冲区是否有数据(>0 表示有数据) | | `ser.readline()` | 读取一行数据(直到遇到换行符 `\n`) | | `.decode()` | 将字节数据(bytes)转为字符串(str),默认UTF-8编码 | | `.strip()` | 去除字符串首尾的空白字符(如`\r`, `\n`, 空格等) | --- #### 2. **完整工作流程** ```mermaid graph TD A[启动循环] --> B{检查缓冲区<br>ser.in_waiting > 0 ?} B -->|是| C[读取一行数据 ser.readline] C --> D[字节转字符串 .decode] D --> E[清理首尾字符 .strip] E --> F[存入变量 line] F --> B B -->|否| G[退出循环] ``` --- #### 3. **关键设计解析** 1. **循环条件**: - `while ser.in_waiting > 0` 确保**持续消费缓冲区数据** - 避免数据堆积导致缓冲区溢出 - 等价逻辑:`while ser.in_waiting:`(Python自动转换非零值为`True`) 2. **数据读取优化**: - `readline()` 按行读取(依赖换行符 `\n` 作为分隔符) - 比`read()`单字节读取更高效 - 适合处理结构化数据(如传感器输出的`温度:25.6℃\n`) 3. **数据清洗**: ```python # 原始数据示例:b' 23.5\r\n' .decode() → " 23.5\r\n" .strip() → "23.5" # 移除首尾控制字符 ``` --- #### 4. **典型应用场景** ```python import serial # 创建串口对象 ser = serial.Serial('/dev/ttyUSB0', baudrate=9600, timeout=1) # [^2] while True: # 核心代码:持续消费缓冲区数据 while ser.in_waiting > 0: line = ser.readline().decode().strip() # 处理有效数据(示例:温度传感器) if line.startswith("Temp:"): temperature = float(line.split(":")[1]) print(f"当前温度: {temperature}℃") ``` --- #### 5. **注意事项** 1. **编码风险**: - 若设备返回非UTF-8数据,需显式指定编码: `.decode('latin1')` 或 `.decode('ascii', errors='ignore')` 2. **超时控制**: - 创建串口时需设置`timeout`参数(如`timeout=0.5`) - 防止`readline()`在缺失`\n`时永久阻塞 3. **性能优化**: - 当高速传输时(如115200bps),可改用: `data = ser.read(ser.in_waiting)` 一次性读取全部缓冲数据 4. **异常处理**: ```python try: line = ser.readline().decode().strip() except UnicodeDecodeError: # 处理编码错误 except serial.SerialException: # 处理串口断开 ``` ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值