街区最短路径问题-简单数论

街区最短路径问题

时间限制: 3000 ms  |  内存限制: 65535 KB
难度: 4
描述
一个街区有很多住户,街区的街道只能为东西、南北两种方向。

住户只可以沿着街道行走。

各个街道之间的间隔相等。

用(x,y)来表示住户坐在的街区。

例如(4,20),表示用户在东西方向第4个街道,南北方向第20个街道。

现在要建一个邮局,使得各个住户到邮局的距离之和最少。

求现在这个邮局应该建在那个地方使得所有住户距离之和最小;

输入
第一行一个整数n<20,表示有n组测试数据,下面是n组数据;
每组第一行一个整数m<20,表示本组有m个住户,下面的m行每行有两个整数0<x,y<100,表示某个用户所在街区的坐标。
m行后是新一组的数据;
输出
每组数据输出到邮局最小的距离和,回车结束;
样例输入
2
3
1 1
2 1
1 2
5
2 9 
5 20
11 9
1 1
1 20
样例输出
2
44
这是一道非常简单的题目,但是我却要提出来,因为这道题目方法之间选择有点巧妙
代码一:暴力循环,因为大小只有0-100
/*
Author: 2486
Memory: 232 KB		Time: 8 MS
Language: G++		Result: Accepted
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int INF=0x3f3f3f3f;
typedef pair<int,int> P;
P a[25];
int n,m;
P Ma,Mi;
int getmin(int x,int y) {
    int mi=0;
    for(int i=0; i<m; i++) {
        mi+=abs(x-a[i].first)+abs(y-a[i].second);
    }
    return mi;
}
int main() {
    scanf("%d",&n);
    while(n--) {
        Ma.second=0,Ma.first=0,Mi.second=INF,Mi.first=INF;
        scanf("%d",&m);
        for(int i=0; i<m; i++) {
            scanf("%d%d",&a[i].first,&a[i].second);
            Ma.first=max(Ma.first,a[i].first);
            Ma.second=max(Ma.second,a[i].second);
            Mi.first=min(Mi.first,a[i].first);
            Mi.second=min(Mi.second,a[i].second);
        }
        int Min=INF;
        for(int i=Mi.first; i<=Ma.first; i++) {
            for(int j=Mi.second; j<=Ma.second; j++) {
                Min=min(Min,getmin(i,j));
            }
        }
        printf("%d\n",Min);
    }
    return 0;
}
        


第二份代码则是比较巧妙了,大家思考
<pre name="code" class="cpp">/*
Author: 2486
Memory: 232 KB		Time: 0 MS
Language: G++		Result: Accepted
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int INF=0x3f3f3f3f;
int a[25],b[25],n,m;
int main() {
    scanf("%d",&n);
    while(n--) {
        scanf("%d",&m);
        for(int i=0; i<m; i++) {
            scanf("%d%d",&a[i],&b[i]);
        }
        int sum=0;
        sort(a,a+m);
        sort(b,b+m);
        for(int i=0;i<m/2;i++){
            sum+=a[m-i-1]-a[i]+b[m-i-1]-b[i];
        }
        printf("%d\n",sum);
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值