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
",find(0,n-1));
return 0;
}