zoukankan      html  css  js  c++  java
  • 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
    ",find(0,n-1));
    	return 0;
    }
    
  • 相关阅读:
    程序启动冲出UAC解决Win UAC问题的编程经验
    代码服务器端Tornado实现聊天室功能(websocket)
    选中菜单android中的显示跳转和隐式跳转
    提交优化Oracle Tuning Log File Sync 等待事件的几种策略
    对象类Effective Java:Ch3_Methods:Item11_谨慎重写clone()
    视频教程视频Java+PHP+.NET海量教程来了 500G教程
    应用性能Intel MIC适合什么样的应用程序
    资源页面dwr的ajax实现
    登录用户Eclipse中SVN访问用户的变更办法
    内存释放[置顶] Cocos2dx 内存管理心得
  • 原文地址:https://www.cnblogs.com/orion7/p/8419552.html
Copyright © 2011-2022 走看看