Codeforces Round #245 (Div. 1) 429D Tricky Function (最近点对 分治)

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).

Example
Input
4
1 0 0 -1
Output
1
Input
2
1 -1
Output
2

题意

给出n个数,求最小的f(i,j)

f(i,j)=(j-i)^2+(sum[j]-sum[i])^2

其中sum表示前缀和。

题解

这个公式很像欧几里得距离,以i为x轴,sum[i]为y轴,问题就转化为最近点对问题了。

#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
const int maxn=1e5+5;
typedef long long LL;
typedef pair<LL,LL> P;
P p[maxn];
int a[maxn];
LL sqr(LL x)
{
    return x*x;
}
LL dis(P x1,P x2)
{
    return sqr(x1.first-x2.first)+sqr(x1.second-x2.second);
}
bool cmpy(int x,int y)
{
    return p[x].second<p[y].second;
}
LL find(int l,int r)
{
    if(l+1==r)
        return dis(p[l],p[r]);
    int mid=(l+r)>>1;
    LL ans=min(find(l,mid),find(mid,r));//递归求解左右两侧的最短距离
    int cnt=0;
    for(int i=l;i<=r;i++)
        if(abs(p[i].first-p[mid].first)<=ans)
            a[cnt++]=i;
    sort(a,a+cnt,cmpy);//筛选的点然后按y轴排序
    for(int i=0;i<cnt;i++)
        for(int j=i+1;j<cnt&&sqr(p[a[j]].second-p[a[i]].second)<ans;j++)//这里可以剪枝
            ans=min(ans,dis(p[a[i]],p[a[j]]));
    return ans;
}
int main()
{
    int n;
    scanf("%d",&n);
    LL sum=0;
    for(int i=0;i<n;i++)
    {
        int x;
        scanf("%d",&x);
        p[i].first=i+1;
        sum+=x;
        p[i].second=sum;
    }
    printf("%lld\n",find(0,n-1));
    return 0;
}

转载于:https://www.cnblogs.com/orion7/p/8419552.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值