当前位置: 首页 > news >正文

算法竞赛进阶指南.沙漠之王

题目

348. 沙漠之王

算法标签: 01 01 01分数规划, 最小生成树

思路

看题目有要求是构建的渠道的总长度和总成本的比值最小, 形式化的表示
k = ∑ L ∑ S k = \frac {\sum L}{\sum S} k=SL

可以转化为

k ⋅ ∑ S − ∑ L = 0 k \cdot \sum S - \sum L = 0 kSL=0

因为 k k k是变化的, 因此可以看做一个函数

f ( x ) = ∑ L − x ⋅ ∑ S f(x) = \sum L - x \cdot \sum S f(x)=LxS

目标求解使得 f ( x ) = 0 f(x) = 0 f(x)=0的最小的 x x x, 因为 f ( x ) f(x) f(x)具有单调性, 因此可以二分 x x x求出答案

代码

#include <iostream>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <vector>using namespace std;const int N = 1010;
const double EPS = 1e-6;struct Village {int x, y, z;
} pos[N];struct Edge {int u, v;double dis, w;
} edges[N * N / 2];int n, idx;
int p[N];double calc(const Village& a, const Village& b) {int dx = a.x - b.x;int dy = a.y - b.y;return sqrt(dx * dx + dy * dy);
}int find(int x) {if (p[x] != x) p[x] = find(p[x]);return p[x];
}bool check(double mid) {for (int i = 0; i < n; ++i) p[i] = i;vector<pair<double, pair<int, int>>> vec;for (int i = 0; i < idx; ++i) {double val = edges[i].w - mid * edges[i].dis;vec.emplace_back(val, make_pair(edges[i].u, edges[i].v));}sort(vec.begin(), vec.end());double res = 0;for (const auto& edge : vec) {int u = edge.second.first;int v = edge.second.second;int fa1 = find(u);int fa2 = find(v);if (fa1 != fa2) {p[fa2] = fa1;res += edge.first;}}return res <= 0;
}void solve() {idx = 0;for (int i = 0; i < n; ++i) {cin >> pos[i].x >> pos[i].y >> pos[i].z;}for (int i = 0; i < n; ++i) {for (int j = i + 1; j < n; ++j) {double dist = calc(pos[i], pos[j]);double cost = abs(pos[i].z - pos[j].z);edges[idx++] = {i, j, dist, cost};}}double l = 0, r = 1e6;while (r - l > EPS) {double mid = (l + r) / 2;if (check(mid)) r = mid;else l = mid;}cout << fixed << setprecision(3) << l << endl;
}int main() {ios::sync_with_stdio(false);cin.tie(0), cout.tie(0);while (cin >> n, n) solve();return 0;
}
http://www.xdnf.cn/news/238825.html

相关文章:

  • 如何加速机器学习模型训练:深入探讨与实用技巧
  • Decode
  • PixONE 六维力传感器:赋能 OEM 机器人,12 自由度精准感知
  • PC端实现微信扫码登录
  • 【Android】Android签名解析
  • TEN:开启实时语音交互的下一代AI Agent引擎
  • 54.[前端开发-前端工程化]Day01-Node-Node安装-前端模块化
  • 多通道协调加载试验机
  • SpringBoot+Redis全局唯一ID生成器
  • Redis应用场景实战:穿透/雪崩/击穿解决方案与分布式锁深度剖析
  • 【数据链路层深度解析】从帧结构到协议实现
  • git 怎样把本地仓库推送到新建的远程仓库
  • 详细解释C++ 泛型模板中的完美转发(Perfect Forwarding)
  • 【自定义控件实现最大高度和最大宽度实现】
  • 2025年天梯题解(L1-8 + L2)
  • 普通IT的股票交易成长史--20250430午
  • 湖北理元理律师事务所:从法律视角看债务优化的合规实践
  • 【Android】36原生Settings新框架PreferenceFragment
  • 生物化学笔记:神经生物学概论05 感受野 视觉中枢 高级视皮层中的信息走向
  • 文章记单词 | 第51篇(六级)
  • 代码随想录算法训练营第三十天(补)
  • 【mysql】执行过程,背诵版
  • 2025平航杯—团队赛
  • 企业的呼入语音智能体是什么样子?
  • 启动Hadoop集群及集群效果
  • 企业数字化转型新动向日渐明鲜,当以“AI为中心”而驱动
  • 分治算法求序列中第K小数
  • RAII 示例
  • 2025-03 机器人等级考试四级理论真题 4级
  • Dify添加ollama模型失败:NewConnectionError: Failed to establish a new connection