SCU 2759 哈希

Description

You know that the first problem of an online judge system should be the "A+B Problem", but TOJ not. What a terrible! So now it comes... Given a series of numbers, your task is to find the largest number C in the sequence, which is the sum of two other numbers A and B in the sequence. Please note that A and B may have the same value, but cannot be the same number.

Input

The first line of each test case is an integer N (1 ≤ N ≤ 1000), which is the amount of the numbers, followed by a line of N numbers. You can assume all the numbers in the sequence are positive and not more than (2^31)-1. The input will be terminated by a zero.

Output

Output one line for each test case, indicating the largest number. If there is no such number, output "-1".

Sample Input

5 8 3 4 3 6 0

Sample Output

6

 

题意:给定一个数组,要求找到最大的一个数,使得他是数组中其他两个数之和。

解题思路:由于测试数据很强n*n*log(n)铁定超时,所以要用哈希来做,首先将数组排序,并存储1000个数,然后从大到小枚举两两之和,找到就退出。

代码:

 

#include<iostream> 
#include<stdio.h> 
#include<string.h> 
#include<algorithm> 
using namespace std; 
typedef long long ll; 
const int mod=100009
int head[102000],tot; 
struct node 

     int next,val; 
}edge[600000]; 
void init() 

     for(int i=0;i<=100009;i++)head[i]=-1;tot=0

bool find(int x) 

        int p=x%mod; 
        for(ll i=head[p];i!=-1;i=edge[i].next) 
        { 
               ll v=edge[i].val; 
               if(v==x)return 1
        } 
       return 0

void add(int x) 

       if(find(x))return
       ll p=x%mod; 
       edge[tot].next=head[p]; 
       edge[tot].val=x; 
       head[p]=tot++; 

ll a[1010]; 
int main() 

         //freopen("data.in","r",stdin); 
        
// freopen("data.out","w",stdout); 
        int i,j,k,m,n; 
         while(~scanf("%d",&n)&&n) 
         { 
                  init(); 
                  long long mm=-1
                  for(i=0;i<n;i++) 
                  { 
                           scanf("%d",&a[i]); 
                           add(a[i]); 
                           if(mm<a[i])mm=a[i]; 
                  } 
                  sort(a,a+n); 
                  int ans=-1
                  for(i=n-1;i>=0;i--) 
                  { 
                           for(j=i-1;j>=0;j--) 
                           { 
                                    if((long long)a[i]+a[j]>mm)continue
                                    k=(a[i]%mod+a[j]%mod)%mod; 
                                    if(find(a[i]+a[j])) 
                                    { 
                                             if(ans<a[i]+a[j])ans=a[i]+a[j]; 
                                             break
                                    } 
                           } 
                  } 
                  printf("%d\n",ans); 
         } 
         return 0

 

posted @ 2013-09-05 22:42  线性无关  阅读(134)  评论(0)    收藏  举报