全排列题目

链接:https://ac.nowcoder.com/acm/problem/202485
来源:牛客网

我们把房间按照笛卡尔坐标系进行建模之后,每个点就有了一个坐标。
假设现在房子里有些纸片需要被收集,收集完纸片你还要回归到原来的位置,你需要制定一个策略来使得自己行走的距离最短。
你只能沿着 x 轴或 y 轴方向移动,从位置 (i,j) 移动到相邻位置 (i+1,j),(i-1,j),(i,j+1) 或 (i,j-1) 距离增加 1。

输入描述:

在第一行中给出一个T,1≤T≤10T, 1 le T le 10T,1T10, 代表测试数据的组数。
对于每组输入,在第一行中给出房间大小,第二行给出你的初始位置。
接下来给出一个正整数 n,1≤n≤10n,1 le n le 10n,1n10 代表纸片的个数。
接下来 n 行,每行一个坐标代表纸片的位置。
保证房间小于 20×2020 imes 2020×20,纸片一定位于房间内。

输出描述:

对于每组输入,在一行中输出答案。
格式参见样例。
示例1

输入

复制
1
10 10
1 1
4
2 3
5 5
9 4
6 5

输出

复制
The shortest path has length 24
这个题数据范围很小,全排列就行

do{

        }while(next_permutation(a+1,a+1+cnt));


#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=1e5+100; 
int a[maxn];
int x[maxn];
int y[maxn];
int main(){
    int t;
    cin>>t;
    while(t--){
        int n,m,sx,sy,cnt;
        cin>>n>>m>>sx>>sy>>cnt; 
        x[0]=x[cnt+1]=sx;
        y[0]=y[cnt+1]=sy;
        a[0]=0;
        a[cnt+1]=cnt+1;
        for(int i=1;i<=cnt;i++){
            cin>>x[i]>>y[i];
            a[i]=i; 
        }
        int ans=0x3f3f3f3f;
        do{
//            for(int i=0;i<=cnt+1;i++){
//                printf("%d ",a[i]);
//            }
            int sum=0;
            for(int i=1;i<=cnt+1;i++){
                int u=a[i],v=a[i-1];
                sum+=abs(x[u]-x[v])+abs(y[u]-y[v]);
            }
            ans=min(ans,sum);
        }while(next_permutation(a+1,a+1+cnt)); 
        printf("The shortest path has length %d
",ans);
    }
    
} 
原文地址:https://www.cnblogs.com/lipu123/p/14604845.html