2020 Winter Holiday 【gmoj2192】 【sum】 【Pseudo-two points】

Title description

Given n numbers a1 ... an, find the minimum value of the absolute value of the two numbers,
that is, | ai + aj | (i is not equal to j)

Input

The first line is a number n
followed by the next line n number a1 ... an

Output

One number ans in one line, the minimum value of the absolute value of two numbers added together

Sample input

5
-2 6 7 7 -8

Sample output

1

Data range limitation

• For 40% of the data, n <= 10 3 , -10 6 <= ai <= 10 6 .
• For 80% of the data, n <= 10 5 , -10 6 <= ai <= 10 6 .
• For 100% data, n <= 10 6 , -10 6 <= ai <= 10 6 .

analysis

The absolute value closest to 1 is definitely the best! (Nonsense ing).
Sort first (required), then use two variables to "close" from two sides to the middle. That is to say, if the sum ( not absolute value ) of the two numbers is negative, the variable on the left moves to the right, and if it is positive, the variable on the right moves to the left. Just play the ring!

Code on

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
long long n,a[1000010],mn=0x3fffff;
int main()
{
	freopen("sum.in","r",stdin);
	freopen("sum.out","w",stdout);
    cin>>n;
    for(int i=1;i<=n;i++)
    {
    	cin>>a[i];
	}
	sort(a+1,a+n+1);
	//for(int i=1;i<=n;i++) cout<<a[i]<<' ';
	long long l=1,r=n,x,y;
	while(l<=r)
	{
		x=abs(a[l]+a[r]);
		y=a[l]+a[r];
		mn=min(mn,x);
		if(y<=0) l++;
		else r--;
	}
	cout<<mn;
	fclose(stdin);
	fclose(stdout);
    return 0;
}

Published 110 original articles · 100 praises · views 8031

Guess you like

Origin blog.csdn.net/dglyr/article/details/104826237