首页 > 其他 > 详细

CF 429D

时间:2015-05-24 11:25:02      阅读:346      评论:0      收藏:0      [点我收藏+]
D - Tricky Function
Time Limit:2000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I64u

Description

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 Input

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

 

 求Min((j-i)^2+(sum(a[i+1]~a[j]))^2
 
我们发现sum(a[i+1]~a[j])=(pre[j]-pre[i])
 
那么我们求的即是(j-i)^2+(pre[j]-pre[i])^2
 
我们把(i,pre[i])抽象成一个点,那么所求即是两点距离
 
Ans即是平面最近点对距离,分治解决
 
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<utility>
#define x first
#define y second

using namespace std;

typedef long long ll;

typedef pair<ll,ll> pi;

pi a[100011],ts[100011],que[100011];
int n,i,x;
ll ans,pre[100011];

ll dis(pi a,pi b)
{
    return (a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y);
}

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

void Solve(int l,int r)
{
    int tc,mid,L,R,i,j;
    ll mx;
    if(l+1>=r){
        if(r==l+1)ans=min(ans,dis(a[l],a[r]));
        return;
    }
    mid=(l+r)/2;
    Solve(l,mid);
    Solve(mid+1,r);
    mx=a[mid].x;
    tc=0;
    for(i=mid;i>=l;i--){
        if((mx-a[i].x)*(mx-a[i].x)>=ans)break;
        ts[++tc]=a[i];
    }
    for(i=mid+1;i<=r;i++){
        if((mx-a[i].x)*(mx-a[i].x)>=ans)break;
        ts[++tc]=a[i];
    }
    sort(ts+1,ts+1+tc,cmpy);
    L=1;R=0;
    for(i=1;i<=tc;i++){
        R++;
        que[R]=ts[i];
        while(L<R&&(que[L].y-que[R].y)*(que[L].y-que[R].y)>=ans)L++;
        for(j=L;j<R;j++)ans=min(ans,dis(que[j],que[R]));
    }
    
}

int main()
{
    scanf("%d",&n);
    for(i=1;i<=n;i++){
        scanf("%d",&x);
        pre[i]=pre[i-1]+x;
        a[i].x=i;a[i].y=pre[i];
    }
    ans=1ll<<60;
    Solve(1,n);
    printf("%I64d\n",ans);
}

 

CF 429D

原文:http://www.cnblogs.com/applejxt/p/4525448.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!