nyoj--7 街区最短路径问题(枚举 or math)

nyoj 7

题解

暴力枚举。

#include <iostream>
#include <cstdio>
#include <fstream>
#include <cstring>
#include <set>
#include <cmath>
#include <algorithm>
using namespace std;

const int maxn = 20;
const int inf  = 1 << 30;
int   x[maxn], y[maxn], n;

int calc(int i, int j){
    int sum = 0;
    for(int k = 0; k < n; ++k)
    {
        sum += abs(i - x[k]) + abs(j - y[k]);
    }
    return sum;
}

int main()
{
    //fstream cin("data.in");
    int t;
    for(cin >> t; t--; )
    {
        cin >> n;
        for(int i = 0; i < n; ++i){
            cin >> x[i] >> y[i];
        }
        int ans = inf;
        for(int i = 0; i < 100; ++i)
        {
            for(int j = 0; j < 100; ++j)
            {
                int tmp = calc(i, j);
                ans = min(ans, tmp);
            }
        }
        cout << ans << endl;
    }

    return 0;
}

发现别人一种更优解法。
设邮局坐标 (x,y) ,问题转化为求解

min(|xix|)+min(|yiy|)

题目性质,这里 x y可分别求解,这式子可以表示为数轴上有 n 个点,求一点到其他各点的距离之和最小。
如果n为奇数,这点就是中间一点,否则是中间两点的中间点,两种情况下都有 最小和 = n/2i=1(xnixi) .
画下图不难理解。

#include <iostream>
#include <cstdio>
#include <fstream>
#include <cstring>
#include <set>
#include <cmath>
#include <algorithm>
using namespace std;

const int maxn = 20;
const int inf  = 1 << 30;
int   x[maxn], y[maxn], n;

int main()
{
    //fstream cin("data.in");
    int t;
    for(cin >> t; t--; )
    {
        cin >> n;
        for(int i = 0; i < n; ++i) cin >> x[i] >> y[i];

        sort(x, x + n);
        sort(y, y + n);
        int ans = 0;
        for(int i = 0; i < n / 2; ++i)
            ans += x[n - 1 - i] - x[i] + y[n - 1 - i] - y[i];
        cout << ans << endl;

    }

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值