Lecture Sleep

本文介绍了一个算法问题,即如何通过一次干预使朋友Mishka在数学讲座中记录最多定理。通过对讲座每分钟讲述定理数量及Mishka注意力状态的分析,采用预处理和滑动窗口的方法,有效地解决了此问题。

Lecture Sleep

题目

Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute.
Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka’s behavior. If Mishka is asleep during the i-th minute of the lecture then ti will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told — ai during the i-th minute. Otherwise he writes nothing.
You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n - k + 1. If you use it on some minute i then Mishka will be awake during minutes j such that and will write down all the theorems lecturer tells.
You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.

Input

The first line of the input contains two integer numbers n and k (1 ≤ k ≤ n ≤ 10^5) — the duration of the lecture in minutes and the number of minutes you can keep Mishka awake.
The second line of the input contains n integer numbers a1, a2, … an (1 ≤ ai ≤ 10^4) — the number of theorems lecturer tells during the i-th minute.
The third line of the input contains n integer numbers t1, t2, … tn (0 ≤ ti ≤ 1) — type of Mishka’s behavior at the i-th minute of the lecture.

Output

Print only one integer — the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.

Example

input

6 3
1 3 5 2 5 4
1 1 0 1 0 0

output

16

思路

由题意要求从某个位置m开始,使t[m]~t[m+k-1]中非1元素全为1后,整体t[i]为1对应的所有a[i]累积值最大,并输出该最大值。因此必须从m=0开始枚举位置m,将每个位置所得的累积值相比较。
由于1 ≤ k ≤ n ≤ 10^5,k的范围可能非常大,如果直接双重循环,时间复杂度会很大,所以必须降低时间复杂度。
预先处理a[]数组中,对应t[]为0的元素,定义一个pre[]数组,pre[i]记录a[0]~a[i]中对应t[]=0的元素值之和。枚举位置时,pre[m+k-1]-pre[m-1]即可得到从m位置开始时对应t[]=0的元素值之和,再加上已经求好的整个a[]数组中原本就对应t[]为1的元素值之和,在每个位置m施加作用的累积结果。

代码

#include <bits/stdc++.h>
using namespace std;
const int maxn=1e5+5;
int a[maxn];
int t[maxn];
int pre[maxn];

int main()
{
    int n,k;
    int s=0;
    int temp=0;
    cin>>n>>k;
    for(int i=1;i<=n;i++) cin>>a[i];
    for(int i=1;i<=n;i++)
    {
        cin>>t[i];
        if(t[i]) temp+=a[i];
    }
    memset(pre,0,sizeof(pre));
    pre[0]=0;
    for(int i=1;i<=n;i++)
    {
        if(t[i]) pre[i]=pre[i-1]+0;
        if(!t[i]) pre[i]=pre[i-1]+a[i];
    }
    for(int i=1;i<=n;i++)
    {
        s=max(s,(pre[i+k-1]-pre[i-1]));
    }
    s+=temp;
    cout<<s<<endl;
}
# api.py from flask import Flask, jsonify import subprocess, uuid, os, sys, threading, time, psutil app = Flask(__name__) PY = sys.executable BASE = os.path.dirname(os.path.abspath(__file__)) # 保存子进程句柄 {tag: {"p": Popen, "lid": lecture_id}} PROCS = {} # --------- 工具 --------- def _start(script: str, tag: str): if PROCS.get(tag): return f"{tag} 已在运行" lecture_id = f"{tag}_{uuid.uuid4().hex[:6]}" with open(os.devnull, 'wb') as dev: p = subprocess.Popen([PY, script, lecture_id], cwd=BASE, stdout=dev, stderr=dev) PROCS[tag] = {"p": p, "lid": lecture_id} return f"{tag} 启动成功" def _stop(tag: str): item = PROCS.pop(tag, None) if not item: return f"{tag} 未在运行" parent = psutil.Process(item["p"].pid) for c in parent.children(recursive=True): c.kill() parent.kill() parent.wait() return f"{tag} 已停止" # --------- 路由 --------- @app.get("/") def index(): return jsonify({"msg": "AI-pop-quiz API", "running": list(PROCS.keys())}) @app.post("/start/<tag>") def start(tag): if tag not in ("ppt", "voice"): return jsonify({"error": "tag 只能是 ppt 或 voice"}), 400 msg = _start({"ppt": "ppt_ocr.py", "voice": "recorder.py"}[tag], tag) return jsonify({"msg": msg}) @app.post("/stop/<tag>") def stop(tag): if tag not in ("ppt", "voice"): return jsonify({"error": "tag 只能是 ppt 或 voice"}), 400 msg = _stop(tag) return jsonify({"msg": msg}) # --------- 随 Flask 启动 --------- def _boot(): time.sleep(1) print(_start("ppt_ocr.py", "ppt")) print(_start("recorder.py", "voice")) if __name__ == '__main__': threading.Thread(target=_boot, daemon=True).start() app.run(host='0.0.0.0', port=8000, debug=False) 这是我的代码
最新发布
11-24
由于没有提供具体的使用 Flask 框架编写的包含启动停止子进程、处理特定 tag 的启动停止请求的代码,下面给出一个示例代码并进行审查优化。 ### 示例代码 ```python import subprocess from flask import Flask, request app = Flask(__name__) processes = {} @app.route('/start/<tag>', methods=['POST']) def start_process(tag): try: command = request.json.get('command') if command: process = subprocess.Popen(command, shell=True) processes[tag] = process return f"Process with tag {tag} started successfully", 200 else: return "Command not provided", 400 except Exception as e: return f"Error starting process: {str(e)}", 500 @app.route('/stop/<tag>', methods=['POST']) def stop_process(tag): try: if tag in processes: process = processes[tag] process.terminate() del processes[tag] return f"Process with tag {tag} stopped successfully", 200 else: return f"Process with tag {tag} not found", 404 except Exception as e: return f"Error stopping process: {str(e)}", 500 if __name__ == '__main__': app.run(debug=True) ``` ### 审查优化 1. **安全性问题**:在当前代码中,`subprocess.Popen` 使用了 `shell=True`,这可能存在安全风险,因为如果用户输入的命令包含恶意代码,可能会被执行。可以改为使用 `shell=False` 并传递一个参数列表。 ```python import subprocess from flask import Flask, request app = Flask(__name__) processes = {} @app.route('/start/<tag>', methods=['POST']) def start_process(tag): try: command = request.json.get('command') if command: command_list = command.split() # 将命令字符串拆分为列表 process = subprocess.Popen(command_list, shell=False) processes[tag] = process return f"Process with tag {tag} started successfully", 200 else: return "Command not provided", 400 except Exception as e: return f"Error starting process: {str(e)}", 500 @app.route('/stop/<tag>', methods=['POST']) def stop_process(tag): try: if tag in processes: process = processes[tag] process.terminate() del processes[tag] return f"Process with tag {tag} stopped successfully", 200 else: return f"Process with tag {tag} not found", 404 except Exception as e: return f"Error stopping process: {str(e)}", 500 if __name__ == '__main__': app.run(debug=True) ``` 2. **错误处理**:可以添加更详细的错误日志记录,方便后续排查问题。可以使用 Python 的 `logging` 模块。 ```python import subprocess import logging from flask import Flask, request app = Flask(__name__) processes = {} logging.basicConfig(level=logging.ERROR) @app.route('/start/<tag>', methods=['POST']) def start_process(tag): try: command = request.json.get('command') if command: command_list = command.split() process = subprocess.Popen(command_list, shell=False) processes[tag] = process return f"Process with tag {tag} started successfully", 200 else: return "Command not provided", 400 except Exception as e: logging.error(f"Error starting process with tag {tag}: {str(e)}") return f"Error starting process: {str(e)}", 500 @app.route('/stop/<tag>', methods=['POST']) def stop_process(tag): try: if tag in processes: process = processes[tag] process.terminate() del processes[tag] return f"Process with tag {tag} stopped successfully", 200 else: return f"Process with tag {tag} not found", 404 except Exception as e: logging.error(f"Error stopping process with tag {tag}: {str(e)}") return f"Error stopping process: {str(e)}", 500 if __name__ == '__main__': app.run(debug=True) ``` 3. **资源管理**:可以添加一个清理机制,在 Flask 应用关闭时,确保所有子进程都被停止。 ```python import subprocess import logging from flask import Flask, request app = Flask(__name__) processes = {} logging.basicConfig(level=logging.ERROR) @app.route('/start/<tag>', methods=['POST']) def start_process(tag): try: command = request.json.get('command') if command: command_list = command.split() process = subprocess.Popen(command_list, shell=False) processes[tag] = process return f"Process with tag {tag} started successfully", 200 else: return "Command not provided", 400 except Exception as e: logging.error(f"Error starting process with tag {tag}: {str(e)}") return f"Error starting process: {str(e)}", 500 @app.route('/stop/<tag>', methods=['POST']) def stop_process(tag): try: if tag in processes: process = processes[tag] process.terminate() del processes[tag] return f"Process with tag {tag} stopped successfully", 200 else: return f"Process with tag {tag} not found", 404 except Exception as e: logging.error(f"Error stopping process with tag {tag}: {str(e)}") return f"Error stopping process: {str(e)}", 500 @app.teardown_appcontext def cleanup(exception=None): for tag, process in list(processes.items()): try: process.terminate() del processes[tag] except Exception as e: logging.error(f"Error cleaning up process with tag {tag}: {str(e)}") if __name__ == '__main__': app.run(debug=True) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值