as -10^9 < = a [N] < = 10^9浮點數,使用堆來避免丟失精度。
如果你不知道什麼是堆及其操作,你可以在大多數算法書籍和網頁上找到它們。
這裏是僞代碼,我認爲我,J,M,給出了N:
build a[i...j] to a max-heap heap1;
build a[m...n] to a min-heap heap2;
size1 = j-i+1;
size2 = n-m+1;
while(size1>1) {
n1 = extractmax();
n2 = extractmax();
temp = n1+n2;
insert(heap1,temp)
}
//do the same thing to heap2,but use extractmin() instead of extractmax()
result = abs(a[i])+a[m];
如果I,J,M,N不給,由分區找到他們,這是快速排序的典型部分。
例如
a[0] = 0;
i=j=0;//a[0] is useless, and 1 ≤ i ≤ j < m ≤ n ≤ N
m=n=N;
if(a[N]<=0)
temp = a[N];
a[N] = -1;
//pre: a[i...j] is non-positive
a[m...n] is non-negetive
while(j<=m+1){
while(a[j+1]<=0)
j++;
while(a[m-1]>=0)
m--;
if(j+1>m)
break;
swap(a[j+1],a[m-1]);
j++;m--;
}
if(temp<=0) { //insert a[N] back
a[N] = a[m];
a[m] = temp;
j = m;
m++;
}
//then you will have checked all elements
//and make sure that non-positive elements are consecutive
//so as to non-negative elements
//now you have i,j,m,n to run pseudo-code at the beginning.
//although i,j may be not more than 0,it depends on the data in your array.
來源
2013-06-13 03:26:57
vvy
討厭問,但你是怎麼試試?你有什麼特別的問題? – nneonneo
@nneonneo:我不知道如何解決這個問題,我不知道要使用哪種算法,我從來沒有解決過這種類型的問題,我從最後一天開始討論這個問題,而且我沒有得到任何邏輯來解決這個問題。誠摯的建議我算法,因爲我會非常感謝你 – alankrita
你是否陷入了第一階段,第二階段或第三階段? – Patashu