[洛谷 P5633] 最小度限制生成树(WQS 二分) | 错题本

文章目录

题目

[洛谷 P5633] 最小度限制生成树

分析

s s s 的邻接边弄一个 Δ \Delta Δ 值加在边权上,然后做最小生成树,易知 Δ \Delta Δ 越大, s s s 的度越小,因此可以 WQS 二分。实现把 s s s 的邻接边和非邻接边分别排好序,做的时候归并即可。

代码

#include <bits/stdc++.h>

int Read() {
   
   
	int x = 0; bool f = false; char c = getchar();
	while (c < '0' || c > '9')
		f |= c == '-', c = getchar();
	while (c >= '0' && c <= '9')
		x = x * 10 + (c ^ 48), c = getchar();
	return f ? -x : x;
}

typedef std::pair<int, int
### 动态规划中的凸优化 动态规划(Dynamic Programming, DP)是一种通过分解子问题来解决复杂问题的方法。然而,在某些情况下,标准的动态规划方法可能效率较低,因此引入了凸优化技术以加速计算过程。当状态转移方程具有单调性和凸性时,可以利用这些性质进一步减少时间复杂。 #### 凸优化的核心思想 如果一个问题的状态转移函数满足某种形式的凸性条件,则可以通过维护决策点集合的方式降低每次更新的时间开销。具体来说,对于形如 \( dp[i] = \min_{j} (dp[j] + cost(i,j)) \) 的状态转移方程,其中 \( cost(i,j) \) 是关于 \( j \) 单调或者呈现特定形状的函数,那么可以用斜率优化等技巧提高性能[^1]。 ```python def convex_optimization_dp(n, costs): """ 使用凸优化处理动态规划问题的一个简单例子。 参数: n: 状态数量 costs: 成本数组 返回: 最优解的结果列表 """ dp = [0] * (n + 1) deque = [] for i in range(1, n + 1): while len(deque) >= 2 and slope(deque[-2], deque[-1]) <= -costs[i]: deque.pop() k = deque[0] dp[i] = dp[k] + costs[i] * (i - k) while len(deque) >= 2 and cross_product(deque[-2], deque[-1], i) <= 0: deque.pop() deque.append(i) return dp[n] def slope(x, y): """ 计算两点之间的斜率 """ return (f(y) - f(x)) / (y - x) def cross_product(a, b, c): """ 判断三点共线情况下的叉积方向 """ return (b-a)*(g(c)-g(b))-(c-b)*(g(b)-g(a)) ``` --- ### WQS二分算法详解 WQS二分(Weighted Queue Sliding Binary Search)主要用于求解带有额外约束条件的最优化问题。它通常应用于组合优化领域,尤其是涉及分配资源或物品的情况下。其核心在于调整目标函数中的权重参数,使得最终方案既满足约束又达到全局最优。 #### 实现细节 假设我们有一个背包容量为C的商品集S={a_1,a_2,...,a_n},每件商品有重量w_i和价值v_i,并且存在一个附加限制——最多只能选K件商品。此时可以直接采用如下策略: 1. 定义辅助变量λ作为惩罚因子; 2. 构造新的效用函数F'(x)(v_i-w_i*λ),并尝试最大化该表达式的值; 3. 调整λ直至选出恰好k个元素为止; 这种方法能够有效应对多种变体问题,比如多重背包、区间覆盖等问题。 ```python from bisect import insort_right def wqs_binary_search(items, capacity, max_count): low, high = min(item['weight'] for item in items), sum(item['value']/item['weight'] for item in items) def check(lambda_val): total_weight = 0 count = 0 sorted_items = sorted((item['value'] - lambda_val * item['weight'], idx) for idx,item in enumerate(items)) res = [] current_sum = 0 for val,idx in reversed(sorted_items[:max_count]): if total_weight + items[idx]['weight']<=capacity: total_weight +=items[idx]['weight'] current_sum+=val+lambda_val*items[idx]['weight'] insort_right(res,(current_sum,-total_weight)) best=next(iter(res or [(float('-inf'),)]))[0] return best>=sum(itm['value']for itm in items[:len(res)])and(best,total_weight)==res[-1] eps = 1e-7 while abs(high-low)>eps: mid=(low+high)/2. flag=check(mid) if not flag: low=mid else: high=mid opt_lambda=(low+high)/2. _,solution=check(opt_lambda) return solution,opt_lambda ``` --- ### 带权二分的应用场景 带权二分本质上是对传统二分查找的一种扩展,允许我们在搜索过程中考虑不同选项的重要性差异。这种技术广泛用于图论、网络流等领域,特别是在寻找最小割/最大流路径时非常有用。 例如,在Dijkstra算法中加入优先级队列支持负边权的情况就是一种典型实例。通过对节点间距离赋予适当权重系数,我们可以更灵活地控制寻路行为,从而适应更多实际需求。 ```python import heapq def dijkstra_with_weights(graph, start_node, weight_func=lambda u,v,w:w): distances = {node : float('infinity') for node in graph} previous_nodes = {} pq = [] distances[start_node]=0 heapq.heappush(pq,[distances[start_node],start_node]) while pq: curr_dist,node=heapq.heappop(pq) if curr_dist>distances[node]: continue for neighbor,edge_weight in graph[node].items(): distance=curr_dist+weight_func(node,neighbor,edge_weight) if distance<distances[neighbor]: distances[neighbor]=distance previous_nodes[neighbor]=node heapq.heappush(pq,[distance,neighbor]) return distances,previous_nodes ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值