平面最近点对

#include <iostream>
#include <algorithm>
using namespace std;

typedef long long ll;
const int maxn = 1e5+5;
 
struct node{
	ll x,y;
	bool operator<(const node&n)const {
		return x < n.x;
	}
};
node a[maxn],c[maxn],tmp[maxn];
node Ltmp[maxn],Rtmp[maxn];
ll v[maxn],sum[maxn];

int lcnt, rcnt;
 
ll dis(node A, node B) {
    return (A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y);
}


void merge(int L, int mid, int R) {
    lcnt = 0;         
    int i = L, j = mid + 1;                
    while(i <= mid && j <= R) {
        if(a[i].y != a[j].y ? a[i].y < a[j].y : a[i].x < a[j].x) {
            tmp[++ lcnt] = a[i];
            i ++;
        }else {
            tmp[++ lcnt] = a[j];
            j ++;
        }
    }
    while(i <= mid) {                   
        tmp[++ lcnt] = a[i];
        i ++;
    }
    while(j <= R) {                    
        tmp[++ lcnt] = a[j];
        j ++;
    }
    for(int i = 1; i <= lcnt; i ++) {  
        a[L + i - 1] = tmp[i];
    }
}


ll find(int l, int r) {              
    if(l >= r) return 1e18;       
    int mid  = (l + r) >> 1;
    ll midx = a[mid].x;
    ll D = min(find(l,mid), find(mid+1,r));
    lcnt = 0;
    for(int i = l; i <= mid; i ++) {  
        if((midx - a[i].x)*(midx - a[i].x) <= D) {
            Ltmp[++ lcnt] = a[i];
        }
    }
    rcnt = 0;
    for(int i = mid+1; i <= r; i ++) {    
        if((a[i].x - midx)*(a[i].x - midx) <= D) {
            Rtmp[++ rcnt] = a[i];
        }
    }
    int lpos = 1, rpos = 0;
    for(int i = 1; i <= lcnt; i ++) { 
        while(rpos < rcnt && 
            (Rtmp[rpos + 1].y < Ltmp[i].y || (Rtmp[rpos + 1].y - Ltmp[i].y)*(Rtmp[rpos+1].y - Ltmp[i].y) <= D)) {
            rpos ++;
        }
        while(lpos < rcnt && Rtmp[lpos].y < Ltmp[i].y && (Ltmp[i].y - Rtmp[lpos].y)*(Ltmp[i].y - Rtmp[lpos].y) > D) {
            lpos ++;
        }
        for(int j = lpos; j <= rpos; j ++) {
            D = min(D, dis(Ltmp[i],Rtmp[j]));
        }
    }
    merge(l, mid, r);                     
    return D;
}
 
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0),cout.tie(0);
	int n;
	cin >> n;
	n ++;
	a[1].x = -1;
	a[1].y = 0;
	for (int i = 2; i <= n; i++) {
		cin >> v[i];
		sum[i] = sum[i-1] + v[i];
		a[i].x = i-2;
		a[i].y = sum[i];
	}
	sort(a+1,a+1+n);
	cout << find(1,n) << '\n';
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值