题解 | 收集纸片

收集纸片

https://www.nowcoder.com/practice/3897dd2bf85d4361a9490f221ea62343

#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
#define all(a) a.begin(), a.end()
using vi = vector<int>;
using vpii = vector<pair<int, int>>;

void solve() {
    int n, m;cin >> n >> m;
    int x, y;cin >> x >> y;
    int len;cin >> len;
    vpii a(len);
    for (int i = 0;i < len;i++) {
        cin >> a[i].first>>a[i].second;
    }
    vi idx(len);
    for (int i = 0;i < len;i++) {
        idx[i] = i;
    }
    int mn = 1e9;
    do {
        int sum = 0;
        int x0 = x, y0 = y;
        for (int i : idx) {
            auto [xx, yy] = a[i];
            sum += abs(xx - x0) + abs(yy - y0);
            x0 = xx, y0 = yy;
        }
        sum += abs(x - x0) + abs(y - y0);
        mn = min(mn, sum);
    } while (next_permutation(all(idx)));
    cout << "The shortest path has length "<< mn << endl;
}

/*

*/

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);cout.tie(nullptr);
    int t = 1;
    cin >> t;
    for (int i = 1; i <= t; i++) {
        //cout << "----Test " << i << "----" << endl;
        solve();
    }
    return 0;
}

全排列枚举,全排列下标数组对每一种排列模拟路径,取最小值

全部评论

相关推荐

牛客41406533...:回答他在课上学,一辈子待在学校的老教授用三十年前的祖传PPT一字一句的讲解,使用谭浩强红皮书作为教材在devc++里面敲出a+++++a的瞬间爆出114514个编译错误来学这样才显得专业
点赞 评论 收藏
分享
野猪不是猪🐗:还是太卑微了,什么叫放弃本次面试应该说经过评估,贵公司与自己不匹配,决定不再推进后续流程
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务