24h購物| | PChome| 登入
2012-03-23 22:45:05| 人氣2,594| 回應0 | 上一篇 | 下一篇

[UVA][Sort&Search] 10125 - Sumsets

推薦 0 收藏 0 轉貼0 訂閱站台

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

a+b = d-c
將 a+b 的所有可能存起來, d-c 開始用二分搜尋找
#include <stdio.h>
#include <stdlib.h>
typedef struct Element {
int sum, x, y;
};
int cmp1(const void *i, const void *j) {
return *(int *)i - *(int *)j;
}
int cmp2(const void *i, const void *j) {
Element *a, *b;
a = (Element *)i, b = (Element *)j;
return a->sum - b->sum;
}
Element sub[1000000];
int search(int v, int a, int b, int n) {
int l, r, m, i;
l = 0, r = n;
while(l <= r) {
m = (l+r)/2;
if(sub[m].sum > v)
r = m-1;
else if(sub[m].sum < v)
l = m+1;
else {
for(i = m; i <= r; i++) {
if(sub[i].sum != v)
break;
if(a != sub[i].x && a != sub[i].y
&& b != sub[i].x && b != sub[i].y)
return 1;
}

for(i = m-1; i >= l; i--) {
if(sub[i].sum != v)
break;
if(a != sub[i].x && a != sub[i].y
&& b != sub[i].x && b != sub[i].y)
return 1;
}
return 0;
}
}
return 0;
}
int main() {
int n, S[1000], i, j;
while(scanf("%d", &n) == 1 && n) {
for(i = 0; i < n; i++)
scanf("%d", &S[i]);
qsort(S, n, sizeof(int), cmp1);
int m = 0;
for(i = 0; i < n; i++) {
for(j = i+1; j < n; j++) {
sub[m].sum = S[i]+S[j];
sub[m].x = S[i];
sub[m].y = S[j];
m++;
}
}
qsort(sub, m, sizeof(Element), cmp2);
int flag = 0, max = -536870912*2, test;
for(i = n-1; i >= 0; i--) {
if(flag) break;
for(j = 0; j < n; j++) {
if(flag) break;
if(i == j) continue;
test = search(S[i]-S[j], S[i], S[j], m-1);
if(test == 1) {
max = S[i], flag = 1;
}
}
}
if(flag == 0)
puts("no solution");
else
printf("%d\n", max);
}
return 0;
}
 

台長: Morris
人氣(2,594) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA] 11150 - Cola
此分類上一篇:[UVA][Math] 10994 - Simple Addition

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文