#433 - C. Planning(贪心,优先队列)

本文解决了一个关于飞机因技术问题导致的延误调度问题。通过使用优先队列,实现了最小化总延误成本的目标。输入包括航班数量、延误时间和每分钟延误成本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


题目连接:http://codeforces.com/contest/854/problem/C

题目描述

Description

Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.

Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.

All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it’s not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.

Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.

Input

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart.

The second line contains n integers c1, c2, …, cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.

Output

The first line must contain the minimum possible total cost of delaying the flights.

The second line must contain n different integers t1, t2, …, tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.

Sample Input

5 2
4 2 1 10 2

Sample Output

20
3 6 7 4 5

解题思路

题意:飞机要起飞,但是要延误K分钟,一共n架飞机
下面有n个数 第i个数为第i分钟开始每秒损失n[i]金钱,例如4 2 1 10 2,第一分钟开始损失4金钱/分钟,第二分钟,第一架和第二架一共损失6金钱/分钟(都没起飞的情况下)
明白了题意就好办了,做一个优先队列,就是带排序的队列,int回爆,用long long

AC代码

#include<iostream>
#include<queue>
#define MAXN 1000010

using namespace std;

struct node {
    int id, cost;
//  node(int id, int cost):id(id), cost(cost) {};
    bool operator < (const node& n) const { //让队列排序 
        return cost < n.cost;
    }
}cnt[MAXN];

int main() {
    long long n, k; 
    cin >> n >> k;
    priority_queue<node> q;
    long long sum = 0;
    for(long long i = 1; i <= n; i++) {
        cin >> cnt[i].cost;
        cnt[i].id = i;
    } 
    for(long long i = 1; i <= k; i++) q.push(cnt[i]); //把延时的时候可以起飞的飞机放进队列 
    for(long long i = k+1; i <= n+k; i++) {
        if(i <= n) {
            q.push(cnt[i]);//要一个一个放进去,因为不能在本来起飞的时间前起飞 
        }
        node val = q.top();
        q.pop();
        sum += (long long) (i - val.id) * val.cost;//只要优先起飞花费最多的飞机一定是花费最少的 
        cnt[val.id].id = i;
    }
    cout << sum << endl;
    for(long long i = 1; i <= n; i++) {
        cout << cnt[i].id << " ";//这里没哟要求输出格式 
    }
    return 0;
} 
import numpy as np import matplotlib.pyplot as plt import heapq import time import math from tqdm import tqdm class ThreatMap: def __init__(self, width, height, resolution=100): self.width = width self.height = height self.resolution = resolution # meters per grid cell self.terrain = np.zeros((width, height)) self.radars = [] self.fires = [] self.threat_map = np.zeros((width, height, 3)) # [terrain, radar, fire] self.combined_threat = np.zeros((width, height)) self.weights = np.array([0.2, 0.2, 0.3]) # Initial weights [wg, wR, wAA] def generate_terrain(self, terrain_type=&#39;mountain&#39;): if terrain_type == &#39;mountain&#39;: # Generate mountain-like terrain x = np.linspace(0, 10, self.width) y = np.linspace(0, 10, self.height) X, Y = np.meshgrid(x, y) Z = 500 * np.sin(0.5*X) * np.cos(0.5*Y) + 300 self.terrain = Z.T elif terrain_type == &#39;valley&#39;: # Generate valley terrain for i in range(self.width): for j in range(self.height): self.terrain[i, j] = 100 + 50 * np.sin(i/20) + 50 * np.cos(j/20) # Normalize terrain self.terrain = (self.terrain - np.min(self.terrain)) / (np.max(self.terrain) - np.min(self.terrain)) * 1000 def add_radar(self, x, y, direction, max_range, fov=120): self.radars.append({ &#39;pos&#39;: (x, y), &#39;direction&#39;: direction, # in degrees &#39;max_range&#39;: max_range, # in meters &#39;fov&#39;: fov # field of view in degrees }) def add_fire(self, x, y, min_range, max_range): self.fires.append({ &#39;pos&#39;: (x, y), &#39;min_range&#39;: min_range, &#39;max_range&#39;: max_range }) def calculate_terrain_threat(self, x, y, z): h_max = np.max(self.terrain[x, y]) h_min = np.min(self.terrain[x, y]) return (h_max - h_min) / (z - h_max + 1e-5) def calculate_radar_threat(self, x, y, z): threat = 0 for radar in self.radars: rx, ry = radar[&#39;pos&#39;] dx = (x - rx) * self.resolution dy = (y - ry) * self.resolution distance = np.sqrt(dx**2 + dy**2) # Check if within max range if distance > radar[&#39;max_range&#39;]: continue # Check if within field of view angle = math.degrees(math.atan2(dy, dx)) angle_diff = abs((angle - radar[&#39;direction&#39;] + 180) % 360 - 180) if angle_diff > radar[&#39;fov&#39;] / 2: continue # Calculate radar threat with exponential decay if distance < radar[&#39;max_range&#39;]: threat += np.exp(-10 * distance / radar[&#39;max_range&#39;]) return threat def calculate_fire_threat(self, x, y): threat = 0 for fire in self.fires: fx, fy = fire[&#39;pos&#39;] dx = (x - fx) * self.resolution dy = (y - fy) * self.resolution distance = np.sqrt(dx**2 + dy**2) if distance < fire[&#39;min_range&#39;] or distance > fire[&#39;max_range&#39;]: continue threat += np.exp(-10 * (distance - fire[&#39;min_range&#39;]) / (fire[&#39;max_range&#39;] - fire[&#39;min_range&#39;])) return threat def calculate_threats(self, z=500): for i in range(self.width): for j in range(self.height): # Terrain threat self.threat_map[i, j, 0] = self.calculate_terrain_threat(i, j, z) # Radar threat self.threat_map[i, j, 1] = self.calculate_radar_threat(i, j, z) # Fire threat self.threat_map[i, j, 2] = self.calculate_fire_threat(i, j) def variable_weighting(self, T): """Apply variable weighting based on threat levels""" S = np.array([ 1 + np.exp(T[0]), 1 + 1/(T[1] + 1), 1 + 1/(T[2] + 1) ]) W_prime = self.weights * S / np.sum(self.weights * S) return np.sum(W_prime * T) def combine_threats(self): for i in range(self.width): for j in range(self.height): T = self.threat_map[i, j] self.combined_threat[i, j] = self.variable_weighting(T) def plot_threat_map(self): plt.figure(figsize=(12, 10)) plt.imshow(self.combined_threat.T, origin=&#39;lower&#39;, cmap=&#39;hot&#39;) # Plot radars for radar in self.radars: x, y = radar[&#39;pos&#39;] plt.scatter(x, y, s=100, c=&#39;blue&#39;, marker=&#39;^&#39;, label=&#39;Radar&#39;) # Plot fires for fire in self.fires: x, y = fire[&#39;pos&#39;] plt.scatter(x, y, s=100, c=&#39;red&#39;, marker=&#39;o&#39;, label=&#39;Fire&#39;) plt.colorbar(label=&#39;Threat Level&#39;) plt.title(&#39;Combined Threat Map&#39;) plt.xlabel(&#39;X (grid cells)&#39;) plt.ylabel(&#39;Y (grid cells)&#39;) plt.legend() plt.show() class ImprovedARAStar: def __init__(self, threat_map, max_turn_angle=45): self.threat_map = threat_map self.width = threat_map.width self.height = threat_map.height self.resolution = threat_map.resolution self.max_turn_angle = max_turn_angle # in degrees self.k = 0.2 # Threat penalty coefficient self.epsilon = 2.0 # Initial epsilon def heuristic(self, a, b): # Euclidean distance return math.sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2) * self.resolution def get_neighbors(self, node, parent): neighbors = [] # 8-connected grid for dx in [-1, 0, 1]: for dy in [-1, 0, 1]: if dx == 0 and dy == 0: continue x, y = node[0] + dx, node[1] + dy # Check bounds if x < 0 or x >= self.width or y < 0 or y >= self.height: continue # Check turn angle constraint if parent exists if parent: px, py = parent # Vector from parent to current node vec1 = (node[0] - px, node[1] - py) # Vector from current node to neighbor vec2 = (x - node[0], y - node[1]) # Calculate angle between vectors dot = vec1[0]*vec2[0] + vec1[1]*vec2[1] mag1 = math.sqrt(vec1[0]**2 + vec1[1]**2) mag2 = math.sqrt(vec2[0]**2 + vec2[1]**2) if mag1 > 0 and mag2 > 0: cos_angle = dot / (mag1 * mag2) angle = math.degrees(math.acos(max(min(cos_angle, 1), -1))) if angle > self.max_turn_angle: continue neighbors.append((x, y)) return neighbors def path_cost(self, a, b): # Euclidean distance dx = (a[0]-b[0]) * self.resolution dy = (a[1]-b[1]) * self.resolution return math.sqrt(dx**2 + dy**2) def plan(self, start, goal, max_time=60): OPEN = [] CLOSED = {} INCONS = {} # Initialize start node g_score = {start: 0} h_score = self.heuristic(start, goal) T_score = self.threat_map.combined_threat[start[0], start[1]] epsilon_s = self.epsilon * (1 + self.k * T_score) f_score = {start: g_score[start] + epsilon_s * h_score} heapq.heappush(OPEN, (f_score[start], start)) parent = {start: None} start_time = time.time() path_found = False while OPEN and time.time() - start_time < max_time: _, current = heapq.heappop(OPEN) if current == goal: path_found = True break CLOSED[current] = g_score[current] neighbors = self.get_neighbors(current, parent.get(current)) for neighbor in neighbors: # Calculate tentative g_score tentative_g = g_score[current] + self.path_cost(current, neighbor) # Get threat value for neighbor T_neighbor = self.threat_map.combined_threat[neighbor[0], neighbor[1]] epsilon_s = self.epsilon * (1 + self.k * T_neighbor) if neighbor in CLOSED and tentative_g >= CLOSED.get(neighbor, float(&#39;inf&#39;)): continue if tentative_g < g_score.get(neighbor, float(&#39;inf&#39;)): parent[neighbor] = current g_score[neighbor] = tentative_g h_val = self.heuristic(neighbor, goal) f_score[neighbor] = tentative_g + epsilon_s * h_val if neighbor in CLOSED: INCONS[neighbor] = g_score[neighbor] else: heapq.heappush(OPEN, (f_score[neighbor], neighbor)) # Reconstruct path path = [] if path_found: current = goal while current is not None: path.append(current) current = parent.get(current) path.reverse() # Calculate path metrics path_length = 0 threat_value = 0 if len(path) > 1: for i in range(1, len(path)): path_length += self.path_cost(path[i-1], path[i]) threat_value += self.threat_map.combined_threat[path[i][0], path[i][1]] threat_value /= len(path) return path, path_length, threat_value, time.time() - start_time def plot_path(self, path, title="Path Planning Result"): plt.figure(figsize=(12, 10)) plt.imshow(self.threat_map.combined_threat.T, origin=&#39;lower&#39;, cmap=&#39;hot&#39;) # Plot radars for radar in self.threat_map.radars: x, y = radar[&#39;pos&#39;] plt.scatter(x, y, s=100, c=&#39;blue&#39;, marker=&#39;^&#39;, label=&#39;Radar&#39;) # Plot fires for fire in self.threat_map.fires: x, y = fire[&#39;pos&#39;] plt.scatter(x, y, s=100, c=&#39;red&#39;, marker=&#39;o&#39;, label=&#39;Fire&#39;) # Plot path if path: path_x = [p[0] for p in path] path_y = [p[1] for p in path] plt.plot(path_x, path_y, &#39;g-&#39;, linewidth=2, label=&#39;Planned Path&#39;) plt.scatter(path_x[0], path_y[0], s=150, c=&#39;green&#39;, marker=&#39;o&#39;, label=&#39;Start&#39;) plt.scatter(path_x[-1], path_y[-1], s=150, c=&#39;purple&#39;, marker=&#39;*&#39;, label=&#39;Goal&#39;) plt.colorbar(label=&#39;Threat Level&#39;) plt.title(title) plt.xlabel(&#39;X (grid cells)&#39;) plt.ylabel(&#39;Y (grid cells)&#39;) plt.legend() plt.show() # Simulation and Experiment def run_simulation(): # Create threat map width, height = 100, 100 threat_map = ThreatMap(width, height, resolution=100) threat_map.generate_terrain(&#39;mountain&#39;) # Add threats (radars and fires) threat_map.add_radar(20, 80, 45, 5000) threat_map.add_radar(60, 40, 180, 4000) threat_map.add_radar(80, 70, 270, 6000) threat_map.add_fire(30, 30, 1000, 3000) threat_map.add_fire(50, 60, 1500, 4000) threat_map.add_fire(70, 20, 2000, 3500) # Calculate threats threat_map.calculate_threats(z=500) threat_map.combine_threats() # Plot threat map threat_map.plot_threat_map() # Create planner planner = ImprovedARAStar(threat_map) # Define scenarios scenarios = { &#39;Easy&#39;: {&#39;start&#39;: (10, 90), &#39;goal&#39;: (90, 10), &#39;max_time&#39;: 60}, &#39;Medium&#39;: {&#39;start&#39;: (5, 5), &#39;goal&#39;: (95, 95), &#39;max_time&#39;: 120}, &#39;Hard&#39;: {&#39;start&#39;: (10, 50), &#39;goal&#39;: (90, 50), &#39;max_time&#39;: 300} } results = [] # Run simulations for name, params in scenarios.items(): print(f"\nRunning {name} scenario...") start, goal = params[&#39;start&#39;], params[&#39;goal&#39;] # Plan path path, length, threat, time_used = planner.plan(start, goal, params[&#39;max_time&#39;]) if path: print(f"Path found! Length: {length:.2f}m, Avg Threat: {threat:.4f}, Time: {time_used:.2f}s") planner.plot_path(path, title=f"{name} Scenario Path Planning") else: print("No path found!") results.append({ &#39;scenario&#39;: name, &#39;success&#39;: bool(path), &#39;path_length&#39;: length, &#39;avg_threat&#39;: threat, &#39;time&#39;: time_used }) # Print results print("\nSimulation Results:") print("{:<10} {:<10} {:<15} {:<15} {:<10}".format( "Scenario", "Success", "Path Length(m)", "Avg Threat", "Time(s)")) for res in results: print("{:<10} {:<10} {:<15.2f} {:<15.4f} {:<10.2f}".format( res[&#39;scenario&#39;], str(res[&#39;success&#39;]), res[&#39;path_length&#39;], res[&#39;avg_threat&#39;], res[&#39;time&#39;])) # Additional experiments (ablation study) print("\nRunning ablation study...") # Remove fire threats print("\nWithout fire threats:") threat_map_no_fire = ThreatMap(width, height, resolution=100) threat_map_no_fire.terrain = threat_map.terrain.copy() threat_map_no_fire.radars = threat_map.radars.copy() threat_map_no_fire.calculate_threats(z=500) threat_map_no_fire.combine_threats() planner_no_fire = ImprovedARAStar(threat_map_no_fire) path, length, threat, time_used = planner_no_fire.plan(scenarios[&#39;Medium&#39;][&#39;start&#39;], scenarios[&#39;Medium&#39;][&#39;goal&#39;], 120) planner_no_fire.plot_path(path, "Path Planning Without Fire Threats") # Remove radar threats print("\nWithout radar threats:") threat_map_no_radar = ThreatMap(width, height, resolution=100) threat_map_no_radar.terrain = threat_map.terrain.copy() threat_map_no_radar.fires = threat_map.fires.copy() threat_map_no_radar.calculate_threats(z=500) threat_map_no_radar.combine_threats() planner_no_radar = ImprovedARAStar(threat_map_no_radar) path, length, threat, time_used = planner_no_radar.plan(scenarios[&#39;Medium&#39;][&#39;start&#39;], scenarios[&#39;Medium&#39;][&#39;goal&#39;], 120) planner_no_radar.plot_path(path, "Path Planning Without Radar Threats") # Remove terrain threats print("\nWithout terrain threats:") threat_map_no_terrain = ThreatMap(width, height, resolution=100) threat_map_no_terrain.radars = threat_map.radars.copy() threat_map_no_terrain.fires = threat_map.fires.copy() threat_map_no_terrain.calculate_threats(z=500) threat_map_no_terrain.combine_threats() planner_no_terrain = ImprovedARAStar(threat_map_no_terrain) path, length, threat, time_used = planner_no_terrain.plan(scenarios[&#39;Medium&#39;][&#39;start&#39;], scenarios[&#39;Medium&#39;][&#39;goal&#39;], 120) planner_no_terrain.plot_path(path, "Path Planning Without Terrain Threats") if __name__ == "__main__": run_simulation() 生成的航迹为直线,且寻优时间总为0
最新发布
06-12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值