Codefoces 429 D. Tricky Function

本文详细介绍了如何通过编程解决一个竞赛问题,该问题涉及定义一个函数来计算两个数组元素之间的距离,并找出除了自身外的最小距离。通过分析问题并提供一种高效的算法解决方案,读者可以理解如何在限制条件下进行复杂的数据操作。

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


裸的近期点对....

D. Tricky Function
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Iahub and Sorin are the best competitive programmers in their town. However, they can't both qualify to an important contest. The selection will be made with the help of a single problem. Blatnatalag, a friend of Iahub, managed to get hold of the problem before the contest. Because he wants to make sure Iahub will be the one qualified, he tells Iahub the following task.

You're given an (1-based) array a with n elements. Let's define function f(i, j) (1 ≤ i, j ≤ n) as (i - j)2 + g(i, j)2. Function g is calculated by the following pseudo-code:

int g(int i, int j) {
    int sum = 0;
    for (int k = min(i, j) + 1; k <= max(i, j); k = k + 1)
        sum = sum + a[k];
    return sum;
}

Find a value mini ≠ j  f(i, j).

Probably by now Iahub already figured out the solution to this problem. Can you?

Input

The first line of input contains a single integer n (2 ≤ n ≤ 100000). Next line contains n integers a[1]a[2], ..., a[n] ( - 104 ≤ a[i] ≤ 104).

Output

Output a single integer — the value of mini ≠ j  f(i, j).

Sample test(s)
input
4
1 0 0 -1
output
1
input
2
1 -1
output
2


#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

typedef long long int LL;

const int maxn=100100;
const LL INF=1LL<<62;

LL a[maxn];
int n;

struct POINT
{
    LL x,y;
}p[maxn],temp[maxn];

bool cmpxy(POINT a,POINT b)
{
    if(a.x!=b.x) return a.x<b.x;
    return a.y<b.y;
}

bool cmpy(POINT a,POINT b)
{
    return a.y<b.y;
}

inline LL square(LL x)
{
    return x*x;
}

LL dist(POINT a,POINT b)
{
    return square(a.x-b.x)+square(a.y-b.y);
}

LL Close_pair(int left,int right)
{
    LL d=INF;
    if(left==right) return INF;
    if(left+1==right) return dist(p[left],p[right]);
    int mid=(left+right)/2;
    d=min(Close_pair(left,mid),Close_pair(mid+1,right));

    int k=0;
    for(int i=left;i<=right;i++)
    {
        if(square(p[i].x-p[mid].x)<=d)
        {
            temp[k++]=p[i];
        }
    }
    sort(temp,temp+k,cmpy);
    for(int i=0;i<k;i++)
    {
        for(int j=i+1;j<k&&square(temp[i].y-temp[j].y)<d;j++)
        {
            d=min(d,dist(temp[i],temp[j]));
        }
    }

    return d;
}

int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        scanf("%I64d",a+i);
        p[i].x=i;
        p[i].y=p[i-1].y+a[i];
    }
    sort(p+1,p+1+n,cmpxy);
    printf("%I64d\n",Close_pair(1,n));
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值