目录
题意:题目给出n(n <= 18)个点的二维坐标,并说明某些点是被固定了的,其余则没固定,要求添加一些边,使得还没被固定的点变成固定的,
要求总长度最短。
析:由于这个 n 最大才是18,比较小,所以我们考虑是状压DP,当一不固定的点和两个固定的点相连时,这个点也就固定了,这个点以后也是可以使用的,
每次选点都是先固定中最短的两个点保证局部最优。
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | #include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <string> #include <algorithm> #include <vector> #include <map> using namespace std ; typedef long long LL; typedef pair< int , int > P; const int INF = 0x3f3f3f3f; const double inf = 0x3f3f3f3f3f3f3f; const int maxn = (1<<19); struct Node{ int x, y, fx; }; Node a[20]; double d[maxn]; int n; double dis( const Node &p, const Node &q){ return sqrt ((p.x-q.x) * (p.x-q.x) + (p.y-q.y) * (p.y-q.y)); } double dist( int s, int cur){ double num[20]; int cnt = 0; for ( int i = 0; i < n; ++i) if (s & (1<<i)) num[cnt++] = dis(a[cur], a[i]); sort(num, num+cnt); return cnt < 2 ? -1 : num[0] + num[1]; } int main(){ int m; while ( scanf ( "%d" , &n) == 1 && n){ for ( int i = 0; i < (1<<n); ++i) d[i] = inf; int start = 0; int e = 1 << n; for ( int i = 0; i < n; ++i){ scanf ( "%d %d %d" , &a[i].x, &a[i].y, &a[i].fx); if (a[i].fx) start |= (1<<i); } d[start] = 0; for ( int i = start; i < e; ++i){ if (d[i] == inf) continue ; for ( int j = 0; j < n; ++j){ if (i & (1<<j)) continue ; double di = dist(i, j); if (di >= 0) d[i|(1<<j)] = min(d[i|(1<<j)], d[i]+di); } } d[e-1] == inf ? printf ( "No Solution\n" ) : printf ( "%.6lf\n" , d[e-1]); } return 0; } |
分类:
动态规划(DP)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)