UVA - 10125 Sumsets

題目:

Problem C - Sumsets

Given S, a set of integers, find the largest d such that a + b + c = d where a, b, c, and d are distinct elements of S.

Input

Several S, each consisting of a line containing an integer 1 <= n <= 1000 indicating the number of elements in S, followed by the elements of S, one per line. Each element of S is a distinct integer between -536870912 and +536870911 inclusive. The last line of input contains 0.

Output

For each S, a single line containing d, or a single line containing "no solution".

Sample Input

5
2 
3 
5 
7 
12
5
2 
16 
64 
256 
1024
0

Output for Sample Input

12
no solution

#include <cstdlib>  
#include <cstdio>  
#include <cstring>  
#include <string>  
#include <algorithm>  
using namespace std;  
  
const int MAXN = 10000003;  
const int MAXSIZE = 1030;  
  
int n;  
int rear;  
  
struct node  
{  
    int i, j;  
}st[MAXSIZE*MAXSIZE];  
  
int first[MAXN], next[MAXSIZE*MAXSIZE];  
int A[MAXSIZE];  
int sum[MAXSIZE*MAXSIZE];  
  
void init()  
{  
    rear = 0;  
    memset(first, -1, sizeof(first));  
}  
  
int hash(int s)  
{  
    int h = s & 0x7fffffff;  
    return h % MAXN;  
}  
  
void insert(int s)  
{  
    int h = hash(sum[s]);  
    next[s] = first[h];  
    first[h] = s;  
}  
  
int find(int i, int j, int s)  
{  
    int h = hash(s);  
    for(int v = first[h]; v != -1; v = next[v])  
    {  
        if(s == sum[v] && st[v].i != i && st[v].i != j && st[v].j != i && st[v].j != j) return 1;  
    }  
    return 0;  
}  
  
void read_case()  
{  
    init();  
    for(int i = 0; i < n; i++) scanf("%d", &A[i]);  
    sort(A, A+n);  
    for(int i = 0; i < n; i++)  
    {  
        for(int j = i+1; j < n; j++)  
        {  
            st[rear].i = i, st[rear].j = j;  
            sum[rear] = A[i]+A[j];  
            insert(rear);  
            rear++;  
        }  
    }  
}  
  
void solve()  
{  
    read_case();  
    for(int i = n-1; i >= 0; i--)  
    {  
        for(int j = 0; j < n; j++) if(i != j)  
        {  
            if(find(i, j, A[i]-A[j]))  
            {  
                printf("%d\n", A[i]);  
                return ;  
            }  
        }  
    }  
    printf("no solution\n");  
}  
  
int main()  
{  
    while(scanf("%d", &n) && n)  
    {  
        solve();  
    }  
    return 0;  
}  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章