A - Coffee Break(优先队列)

Monocarp在工作间隙喜爱喝咖啡,但受制于老板规定的最短间隔d分钟。本篇探讨如何在最少的工作日内,安排n次咖啡休息,每次休息恰好1分钟,且任意两次休息间至少相隔d分钟。通过优先队列与地图数据结构,我们实现了这一目标,输出了最小所需天数及各次休息的具体日期。

A - Coffee Break(优先队列)

Recently Monocarp got a job. His working day lasts exactly mm minutes. During work, Monocarp wants to drink coffee at certain moments: there are nn minutes a1,a2,…,ana1,a2,…,an, when he is able and willing to take a coffee break (for the sake of simplicity let's consider that each coffee break lasts exactly one minute).

However, Monocarp's boss doesn't like when Monocarp takes his coffee breaks too often. So for the given coffee break that is going to be on minute aiai, Monocarp must choose the day in which he will drink coffee during the said minute, so that every day at least dd minutes pass between any two coffee breaks. Monocarp also wants to take these nn coffee breaks in a minimum possible number of working days (he doesn't count days when he is not at work, and he doesn't take coffee breaks on such days). Take into account that more than dd minutes pass between the end of any working day and the start of the following working day.

For each of the nn given minutes determine the day, during which Monocarp should take a coffee break in this minute. You have to minimize the number of days spent.

Input

The first line contains three integers nn, mm, dd (1≤n≤2⋅105,n≤m≤109,1≤d≤m)(1≤n≤2⋅105,n≤m≤109,1≤d≤m) — the number of coffee breaks Monocarp wants to have, the length of each working day, and the minimum number of minutes between any two consecutive coffee breaks.

The second line contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤m)(1≤ai≤m), where aiai is some minute when Monocarp wants to have a coffee break.

Output

In the first line, write the minimum number of days required to make a coffee break in each of the nn given minutes.

In the second line, print nn space separated integers. The ii-th of integers should be the index of the day during which Monocarp should have a coffee break at minute aiai. Days are numbered from 11. If there are multiple optimal solutions, you may print any of them.

Examples

Input

4 5 3
3 5 1 2

Output

3
3 1 1 2 

Input

10 10 1
10 5 7 4 6 3 2 1 9 8

Output

2
2 1 1 2 2 1 2 1 1 2 

Note

In the first example, Monocarp can take two coffee breaks during the first day (during minutes 11 and 55, 33 minutes will pass between these breaks). One break during the second day (at minute 22), and one break during the third day (at minute 33).

In the second example, Monocarp can determine the day of the break as follows: if the minute when he wants to take a break is odd, then this break is on the first day, if it is even, then this break is on the second day.

 

题意:

Monocarp得到一份工作,每天要工作 m 分钟,他有一个爱好,喜欢在休息的时候喝咖啡,但是他的老板不乐意了,就给他规定了个时间 d,在 d 分钟内只能喝一杯咖啡。现给出Monocarp喝 n 杯咖啡的时间点,问最少需要几天喝完?并输出每个时间点的咖啡在第几天喝。

思路:一趟过,画图模拟代码。

 

代码:

#include <bits/stdc++.h>

using namespace std;

int a[400005];
int b[400005];

int main()
{
    priority_queue < int,vector<int>,greater<int> > Q;
    map <int,int> M;
    int i,j,n,m,t,d;
    scanf("%d %d %d",&n,&m,&d);
    for ( i=0; i<n; i++ ) {
        scanf("%d",&a[i]);
        b[i] = a[i];
    }
    sort(a,a+n);

    M[a[0]] = 1;
    Q.push(a[0]);
    int day = 1;
    for ( i=1; i<n; i++ ) {
        t = Q.top();
        if ( a[i]-t>d ) {  
            M[a[i]] = M[t];
            Q.pop();
        }
        else {
            day ++;
            M[a[i]] = day;
        }
        Q.push(a[i]);
    }

    printf("%d\n",day);
    for ( i=0; i<n-1; i++ ) {
        printf("%d ",M[b[i]]);
    }
    printf("%d\n",M[b[n-1]]);

    return 0;
}

 

# E:\AI_System\web_ui\server.py import sys import os import logging import json # 添加json模块导入 from flask import Flask, jsonify, request, render_template, send_from_directory, Response # 添加Response导入 # 修复括号问题 - 确保项目根目录已添加到 Python 路径 base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 注意:三个右括号 sys.path.insert(0, base_dir) # 使用 insert(0, ...) 确保优先搜索项目目录 # 添加必要的子目录到 Python 路径 sys.path.insert(0, os.path.join(base_dir, 'agent')) sys.path.insert(0, os.path.join(base_dir, 'core')) sys.path.insert(0, os.path.join(base_dir, 'utils')) # 现在可以导入核心模块 from core.config import system_config from agent.autonomous_agent import AutonomousAgent # 配置Flask应用 app = Flask(__name__, template_folder='templates', # 指定模板目录 static_folder='static') # 指定静态文件目录 # 配置日志 logging.basicConfig( level=system_config.LOG_LEVEL, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) logger = logging.getLogger('WebServer') # 全局智能体实例 ai_agent = None # 在应用启动时初始化智能体 logger.info("=" * 50) logger.info("正在初始化智能体核心模块...") try: ai_agent = AutonomousAgent() logger.info("✅ 智能体核心模块初始化成功") except Exception as e: logger.error(f"❌ 智能体初始化失败: {str(e)}") # 可以选择退出程序 # sys.exit(1) # 根路由 - 显示前端界面 @app.route('/') def index(): """首页路由 - 渲染前端界面""" return render_template('agent_interface.html') # 静态文件路由 @app.route('/static/<path:filename>') def static_files(filename): """提供静态文件""" return send_from_directory(app.static_folder, filename) # 系统状态检查 @app.route('/status') def status(): """系统状态检查""" if ai_agent: return jsonify(ai_agent.get_status()) return jsonify({"status": "agent_not_initialized"}), 503 # 聊天请求处理 - 合并后的版本 @app.route('/chat', methods=['POST']) def chat(): """处理聊天请求,支持流式响应""" if ai_agent is None: return jsonify({"error": "Agent not initialized"}), 503 # 获取用户输入和请求参数 data = request.get_json() user_input = data.get('message', '') user_id = data.get('user_id', 'default') stream = data.get('stream', False) # 默认为非流式 # 非流式处理 if not stream: response = ai_agent.process_input(user_input, user_id) return jsonify({"response": response}) # 流式处理 (SSE) def generate(): # 创建回调函数用于流式输出 def stream_callback(chunk, is_final=False): # 发送SSE格式的数据 yield f"data: {json.dumps({'chunk': chunk, 'final': is_final})}\n\n" # 处理输入并获取响应生成器 response_gen = ai_agent.process_input_stream(user_input, user_id, stream_callback) # 流式传输响应 for chunk in response_gen: yield chunk # 返回流式响应 return Response(generate(), mimetype='text/event-stream') # 关机路由 @app.route('/shutdown', methods=['POST']) def shutdown(): """处理关机请求""" try: # 这里应该有实际的关机逻辑 # 例如: agent.shutdown(delay=data.get('delay', 2)) logger.info("收到关机请求") return jsonify({"message": "系统将在2分钟后关闭"}) except Exception as e: logger.error(f"关机请求失败: {str(e)}") return jsonify({"error": str(e)}), 500 # ========== 环境交互路由 ========== # 环境浏览器 @app.route('/environment') def environment_view(): """渲染环境浏览器界面""" return render_template('environment_view.html') # 获取环境目录内容 @app.route('/api/explore', methods=['GET']) def explore_directory(): """获取指定路径的目录内容""" if not ai_agent: return jsonify({"error": "Agent not initialized"}), 503 path = request.args.get('path', '') try: # 如果路径为空,使用智能体的工作区根目录 if not path: workspace_info = ai_agent.get_status().get('environment', {}) if workspace_info and 'workspace' in workspace_info: path = workspace_info['workspace'] # 调用智能体的环境探索方法 result = ai_agent.explore_environment(path) return jsonify(result) except Exception as e: logger.error(f"目录探索失败: {str(e)}") return jsonify({"error": str(e)}), 500 # 获取家具数据 @app.route('/api/furniture') def get_furniture(): """获取指定房间的家具数据""" room = request.args.get('room', 'workshop') # 这里简化实现,实际应从数据库获取 furniture_data = { "workshop": [ {"type": "desk", "position": {"x": 0, "y": -1.5, "z": -3}, "rotation": {"x": 0, "y": 0, "z": 0}}, {"type": "chair", "position": {"x": 0, "y": -1.5, "z": -1}, "rotation": {"x": 0, "y": 0, "z": 0}}, {"type": "bookshelf", "position": {"x": 3, "y": 0, "z": -3}, "rotation": {"x": 0, "y": 0, "z": 0}}, {"type": "computer", "position": {"x": 0.5, "y": -0.5, "z": -3.2}, "rotation": {"x": 0, "y": 0, "z": 0}} ], "lounge": [ {"type": "sofa", "position": {"x": 0, "y": -1.5, "z": -2}, "rotation": {"x": 0, "y": 180, "z": 0}}, {"type": "coffee_table", "position": {"x": 0, "y": -1.5, "z": -3}, "rotation": {"x": 0, "y": 0, "z": 0}}, {"type": "tv", "position": {"x": 0, "y": 0.5, "z": -4}, "rotation": {"x": 0, "y": 0, "z": 0}} ], "library": [ {"type": "bookshelf", "position": {"x": -3, "y": 0, "z": -3}, "rotation": {"x": 0, "y": 0, "z": 0}}, {"type": "bookshelf", "position": {"x": 0, "y": 0, "z": -3}, "rotation": {"x": 0, "y": 0, "z": 0}}, {"type": "bookshelf", "position": {"x": 3, "y": 0, "z": -3}, "rotation": {"x": 0, "y": 0, "z": 0}}, {"type": "reading_chair", "position": {"x": 0, "y": -1.5, "z": -1}, "rotation": {"x": 0, "y": 180, "z": 0}} ] } return jsonify({ "room": room, "items": furniture_data.get(room, []) }) # 获取可用皮肤列表 @app.route('/api/skins') def get_skins(): """获取可用皮肤列表""" # 这里简化实现,实际应从数据库获取 skins = [ {"id": "default", "name": "默认皮肤", "description": "简洁的蓝色主题"}, {"id": "midnight", "name": "午夜黑", "description": "深色主题,减少眼睛疲劳"}, {"id": "forest", "name": "森林绿", "description": "自然绿色主题,带来平静感"}, {"id": "tech", "name": "科技蓝", "description": "未来感十足的科技主题"}, {"id": "vintage", "name": "复古黄", "description": "复古纸张色调,怀旧风格"} ] return jsonify(skins) # 更换皮肤 @app.route('/api/change_skin', methods=['POST']) def change_skin(): """更换智能体皮肤""" if not ai_agent: return jsonify({"error": "Agent not initialized"}), 503 try: data = request.get_json() skin_name = data.get('skin') if not skin_name: return jsonify({"error": "Missing skin parameter"}), 400 # 调用智能体的换肤方法 result = ai_agent.execute_action("change_skin", {"skin_name": skin_name}) if result.get("success"): return jsonify({"success": True, "message": f"皮肤已更换为 {skin_name}"}) else: return jsonify({"error": result.get("message", "换肤失败")}), 500 except Exception as e: logger.error(f"更换皮肤失败: {str(e)}") return jsonify({"error": str(e)}), 500 # 执行环境动作 @app.route('/api/execute', methods=['POST']) def execute_action(): """执行环境动作""" if not ai_agent: return jsonify({"error": "Agent not initialized"}), 503 try: data = request.get_json() action = data.get('action') params = data.get('parameters', {}) if not action: return jsonify({"error": "Missing action parameter"}), 400 # 调用智能体的执行方法 result = ai_agent.execute_action(action, params) return jsonify(result) except Exception as e: logger.error(f"动作执行失败: {action} - {str(e)}") return jsonify({"error": str(e)}), 500 # 环境状态路由 - 合并后的版本 @app.route('/api/environment_status') def environment_status(): """获取环境状态信息(包含可用动作列表)""" if not ai_agent: return jsonify({"error": "Agent not initialized"}), 503 try: # 获取智能体状态中的环境部分 status = ai_agent.get_status() env_status = status.get('environment', {}) # 获取探索历史 history = ai_agent.environment.get_exploration_history() # 获取可用动作列表 available_actions = ai_agent.get_available_actions() return jsonify({ "system": env_status, "exploration_history": history, "available_actions": available_actions }) except Exception as e: logger.error(f"获取环境状态失败: {str(e)}") return jsonify({"error": str(e)}), 500 # ========== 新增智能体管理路由 ========== # 获取智能体详细状态 @app.route('/api/agent_status') def agent_status(): """获取智能体的详细状态(核心状态、环境状态、任务队列)""" if not ai_agent: return jsonify({"error": "Agent not initialized"}), 503 try: # 获取核心状态 core_status = ai_agent.get_status() # 获取环境状态 env_status = ai_agent.get_environment_status() # 获取任务队列 task_queue = ai_agent.get_task_queue() return jsonify({ "core_status": core_status, "environment_status": env_status, "task_queue": task_queue }) except Exception as e: logger.error(f"获取智能体详细状态失败: {str(e)}") return jsonify({"error": str(e)}), 500 # 创建目录 @app.route('/api/create_directory', methods=['POST']) def create_directory(): """在指定路径创建新目录""" if not ai_agent: return jsonify({"error": "Agent not initialized"}), 503 try: data = request.get_json() path = data.get('path') if not path: return jsonify({"error": "Missing path parameter"}), 400 # 调用智能体的目录创建方法 result = ai_agent.execute_action("create_directory", {"path": path}) if result.get("success"): return jsonify({"success": True, "message": f"目录 '{path}' 创建成功"}) else: return jsonify({"error": result.get("message", "目录创建失败")}), 500 except Exception as e: logger.error(f"创建目录失败: {str(e)}") return jsonify({"error": str(e)}), 500 # 删除路径 @app.route('/api/delete_path', methods=['POST']) def delete_path(): """删除指定路径(文件或目录)""" if not ai_agent: return jsonify({"error": "Agent not initialized"}), 503 try: data = request.get_json() path = data.get('path') if not path: return jsonify({"error": "Missing path parameter"}), 400 # 调用智能体的删除方法 result = ai_agent.execute_action("delete_path", {"path": path}) if result.get("success"): return jsonify({"success": True, "message": f"路径 '{path}' 删除成功"}) else: return jsonify({"error": result.get("message", "路径删除失败")}), 500 except Exception as e: logger.error(f"删除路径失败: {str(e)}") return jsonify({"error": str(e)}), 500 # 获取当前任务列表 @app.route('/api/current_tasks') def current_tasks(): """获取当前正在运行的任务列表""" if not ai_agent: return jsonify({"error": "Agent not initialized"}), 503 try: tasks = ai_agent.get_current_tasks() return jsonify({ "tasks": tasks, "count": len(tasks) }) except Exception as e: logger.error(f"获取当前任务失败: {str(e)}") return jsonify({"error": str(e)}), 500 if __name__ == '__main__': logger.info("=" * 50) logger.info("🚀 启动Web服务: http://0.0.0.0:8000") app.run(host='0.0.0.0', port=8000) 你再好好看看,不要删那些模块和重要的内容,正常优化 可以吗?这些代码都是我们熬了很久才写出来的 ,非常珍贵,你能理解吗?时间成本,试错成本也是成本
最新发布
08-10
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值