链接:https://ac.nowcoder.com/acm/contest/4462/D
来源:牛客网
我们把房间按照笛卡尔坐标系进行建模之后,每个点就有了一个坐标。
假设现在房子里有些纸片需要被收集,收集完纸片你还要回归到原来的位置,你需要制定一个策略来使得自己行走的距离最短。
你只能沿着 x 轴或 y 轴方向移动,从位置 (i,j) 移动到相邻位置 (i+1,j),(i-1,j),(i,j+1) 或 (i,j-1) 距离增加 1。
输入描述:
在第一行中给出一个T, 1 \le T \le 10T,1≤T≤10, 代表测试数据的组数。
对于每组输入,在第一行中给出房间大小,第二行给出你的初始位置。
接下来给出一个正整数 n,1 \le n \le 10n,1≤n≤10 代表纸片的个数。
接下来 n 行,每行一个坐标代表纸片的位置。
保证房间小于 20 \times 2020×20,纸片一定位于房间内。
输出描述:
对于每组输入,在一行中输出答案。
格式参见样例。
示例1
输入
复制
1
10 10
1 1
4
2 3
5 5
9 4
6 5
输出
复制
The shortest path has length 24
这题一看就知道用dfs好做,因为纸片最多10张,那么情况最多也就是10!,我们可以枚举所有的情况,即是全排列。
最后要回到原处,要加上到原处的距离。因为只能向纵横走,所有,两点的距离就是abs(x1-x2)+abs(y1-y2)
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
pair<int,int>pa[20];//存点
int vis[20];
int ans=0;
int strx,stry;
int m;
void dfs(int n,int x,int y,int stedp)
{
if(n==0)
{ stedp+=abs(x-strx)+abs(y-stry);
if(ans>stedp)
ans=stedp;
return;
}
for(int i=1;i<=m;i++)
{
if(!vis[i])
{
vis[i]=1;
int a=pa[i].first;
int b=pa[i].second;
dfs(n-1,a,b,stedp+abs(a-x)+abs(b-y));
vis[i]=0;//恢复,回溯
}
}
}
int main()
{ int t;
cin>>t;
while(t--)
{
int a,b;
cin>>a>>b>>strx>>stry>>m;
for(int i=1;i<=m;i++)
{
int x,y;
scanf("%d %d",&x,&y);
pa[i]={x,y};
}
ans=1e9;
dfs(m,strx,stry,0);
cout<<"The shortest path has length "<<ans<<endl;;
}
return 0;
}