杭电hdu 5626 Clarke and points【思维】

本文介绍如何通过生成随机坐标点来计算曼哈顿距离,并从中找出最大值的过程。通过代码实现,理解距离计算原理及最大值求取方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Clarke and points

Problem Description
 
 The Manhattan Distance between point  A(XA,YA) and B(XB,YB) is |XA - XB| + |Xb - YB|;
the coordinate of each point is generated by the followed code.
Input

long long seed;
inline long long rand(long long l, long long r) {
  static long long mo=1e9+7, g=78125;
  return l+((seed*=g)%=mo)%(r-l+1);
}

cin >> n >> seed;
for (int i = 0; i < n; i++)
  x[i] = rand(-1000000000, 1000000000),
  y[i] = rand(-1000000000, 1000000000);
 
Output
For each test case, print a line with an integer represented the maximum distance.
 
Sample Input
2
3 233
5 332
 
Sample Output
1557439953
1423870062
我们知道曼哈顿距离的公式 、当我们计算他的时候,因为有绝对值,所以我们要考虑正负值的关系,这里一共的可能有4种:

正+正、

负+负、

正+负、

负+正、

如果这里大家对官方题解的解释不是很理解,大家可以画出|x+1|+|x-2|的图像,大家对应图像就能明白了,尽量让两个值同正或者是同负的时候值会越来越大、函数图像是一眼就能看出来滴~

蓝后捏:我们对式子进行简单处理、

同正:xa-xb+ya-yb=(xa+ya)-(xb+yb)、同负的时候同理:xb-xa+yb-ya=(xa-ya)-(xb-yb)、将两个式子推出来之后,我们需要做的事情就是维护最大最小的这么几个值、

AC代码:

#include<stdio.h>
#include<ctime>
#include<math.h>
#include<iostream>
#define LL long long int
using namespace std;
LL seed;
inline LL rand(LL l, LL r)
{
    static LL mo = 1e9 + 7, g = 78125;
    return l + ((seed *= g) %= mo) % (r - l + 1);
}
int main()
{
    int T, n;
    LL maxnx, maxny, minnx, minny;
    scanf("%d",&T);
    while(T--) {
        scanf("%d%I64d\n", &n, &seed);
        maxnx = maxny = -0x3f3f3f3f;//这里设定要足够大才行
        minnx = minny = 0x3f3f3f3f;
        for(int i = 1; i <= n; ++i) {
            LL x = rand(-1000000000, 1000000000);
            LL y = rand(-1000000000, 1000000000);
            maxnx = max(maxnx , x + y);
            maxny = max(maxny , x - y);
            minnx = min(minnx , x + y);
            minny = min(minny , x - y);
        }
        printf("%I64d\n", max(maxnx - minnx, maxny - minny));
    }
    return 0;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值