吃奶酪
题目描述
房间里放着 n n n 块奶酪。一只小老鼠要把它们都吃掉,问至少要跑多少距离?老鼠一开始在 ( 0 , 0 ) (0,0) (0,0) 点处。
输入格式
第一行有一个整数,表示奶酪的数量 n n n。
第 2 2 2 到第 ( n + 1 ) (n + 1) (n+1) 行,每行两个实数,第 ( i + 1 ) (i + 1) (i+1) 行的实数分别表示第 i i i 块奶酪的横纵坐标 x i , y i x_i, y_i xi,yi。
输出格式
输出一行一个实数,表示要跑的最少距离,保留 2 2 2 位小数。
样例 #1
样例输入 #1
4
1 1
1 -1
-1 1
-1 -1
样例输出 #1
7.41
提示
数据规模与约定
对于全部的测试点,保证 1 ≤ n ≤ 15 1\leq n\leq 15 1≤n≤15, ∣ x i ∣ , ∣ y i ∣ ≤ 200 |x_i|, |y_i| \leq 200 ∣xi∣,∣yi∣≤200,小数点后最多有 3 3 3 位数字。
提示
对于两个点 ( x 1 , y 1 ) (x_1,y_1) (x1,y1), ( x 2 , y 2 ) (x_2, y_2) (x2,y2),两点之间的距离公式为 ( x 1 − x 2 ) 2 + ( y 1 − y 2 ) 2 \sqrt{(x_1-x_2)^2+(y_1-y_2)^2} (x1−x2)2+(y1−y2)2。
2022.7.13
2022.7.13
2022.7.13:新增加一组
Hack
\text{Hack}
Hack 数据。
先上一个50分的dfs
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
int n;
int v[20];
struct points
{
double x;
double y;
}p[20];
double minn=10000000.0;
double calLength(int a,int b)
{
return(sqrt((p[a].x-p[b].x)*(p[a].x-p[b].x)+(p[a].y-p[b].y)*(p[a].y-p[b].y)));
}
void dfs(int index,int count,double l){
if(count==n)
{
minn=min(minn,l);
return;
}
for(int i=1;i<=n;++i)
{
if(v[i]==0)
{
v[i]=1;
dfs(i,count+1,l+calLength(index,i));
v[i]=0;
}
}
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;++i) scanf("%lf%lf",&p[i].x,&p[i].y);
p[0].x=0,p[0].y=0;
dfs(0,0,0.0);
printf("%.2lf",minn);
return 0;
}
下面,再粘贴一个网上找的满分程序,状态压缩+DFS,顺便把最短路径也输出一下。以供大家学习。
#include <iostream>
#include <cmath>
#include <cstdio>
#include <vector>
using namespace std;
const int N = 20;
int n;
bool vis[N];
double ans = 1e9, dp[65000][20]; // dp用来存路径
struct node {
double x;
double y;
} a[N];
vector<int> best_path, current_path; // 用于记录最佳路径和当前路径
double discal(int l, int m) { // 距离计算函数
return sqrt((a[l].x - a[m].x) * (a[l].x - a[m].x) + (a[l].y - a[m].y) * (a[l].y - a[m].y));
}
void dfs(int sum, int nowi, double dis, int nowdot) {
if (dis > ans) {
return; // 剪枝
}
if (sum == n) {
if (dis < ans) {
ans = dis;
best_path = current_path; // 记录最佳路径
}
return;
}
for (int i = 1; i <= n; i++) {
if (!vis[i]) {
int p = nowdot + (1 << (i - 1));
// 二进制状态压缩从当前点到这个点
if (dp[p][i] != 0 && dp[p][i] <= dis + discal(nowi, i)) {
continue;
}
vis[i] = true;
current_path.push_back(i); // 记录当前路径
dp[p][i] = dis + discal(nowi, i);
dfs(sum + 1, i, dp[p][i], p);
vis[i] = false;
current_path.pop_back(); // 回溯时移除路径记录
}
}
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i].x >> a[i].y;
}
current_path.push_back(0); // 起点添加到路径
dfs(0, 0, 0, 0);
printf("最短路径长度: %.2lf\n", ans);
printf("路径: 0 "); // 起点是0
for (size_t i = 0; i < best_path.size(); i++) {
printf("%d ", best_path[i]);
}
printf("\n");
return 0;
}
输出结果如下: