Description
F S T FST FST作为小朋友,经常会遇到和距离有关的问题,但是他已经厌倦了曼哈顿距离和欧几里德距离,所以 F S T FST FST就定义了一种 F S T FST FST距离。
这种距离并不用于空间或平面中,而运用于 F S T FST FST发明的一些神奇的算法中(唔… …)。
设 i i i号元素的特征值为 A i A_i Ai,则 i i i和 j j j的 F S T FST FST距离是 ∣ i 2 − j 2 ∣ + ∣ A i 2 − A j 2 ∣ |i^2 - j^2|+|A_i^2 - A_j^2| ∣i2−j2∣+∣Ai2−Aj2∣。
为了实现某新的数据结构, F S T FST FST想在一大堆元素中找出距离最大的一对元素,他不关心是哪一对元素,只想求出最大距离。
Input
第一行,一个正整数 n n n,为元素个数。
第二行, n n n个正整数 A i A_i Ai为这 n n n个元素的特征值。
( n ≤ 1 0 5 , A i ≤ 1 0 9 ) (n\le 10^5,A_i\le 10^9) (n≤105,Ai≤109)
Output
一行,一个正整数表示最大距离。 l o n g l o n g long\ long long long请用 l l d lld lld
Sample Input
2
4 3
Sample Output
10
Solution
把 ( i 2 , A i 2 ) (i^2,A_i^2) (i2,Ai2)看作第 i i i个点的二维坐标,问题转化为求 n n n个点中任意两点之间哈密顿距离最大值,假设 i i i点坐标为 ( x i , y i ) (x_i,y_i) (xi,yi),那么 x i , y i x_i,y_i xi,yi在最优答案中的符号只有四种情况 ( ± x i ± y i ) (\pm x_i\pm y_i) (±xi±yi),而对应的另一点的符号与该点相反,那么我们枚举这四种符号的可能,把每个点在该种符号下对答案的贡献排序,最大值即为该种符号的最大贡献,最小值取负即为另一个点对答案的最大贡献,两者加起来维护最优解即为答案,时间复杂度 O ( n l o g n ) O(nlogn) O(nlogn)
Code
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn=100001;
ll x[maxn],y[maxn],z[maxn];
int n;
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
x[i]=1ll*i*i;
scanf("%lld",&y[i]);
y[i]*=y[i];
}
ll ans=0;
for(int i=0;i<=1;i++)
for(int j=0;j<=1;j++)
{
int f1=1,f2=1;
if(i)f1=-1;
if(j)f2=-1;
for(int k=1;k<=n;k++)z[k]=x[k]*f1+y[k]*f2;
sort(z+1,z+n+1);
ans=max(ans,z[n]-z[1]);
}
printf("%lld\n",ans);
return 0;
}