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.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.for each s, a single line containing d, or a single line containing "no solution".
52 3
5 7 125
2 16
64 256
1024
0
12no solution
題目大意:在乙個集合中求出最大的d,d=a+b+c,a,b,c,d屬於這個集合。
解析:這題可以把 a+b+c=d,轉換為 a+b = d-c,這樣就可以減少迴圈的次數。其中d和c用for來遍歷,a+b用二分來查詢出相應的值。
#include#include#includeusing namespace std;
const int n = 1005;
int n;
int num[n];
void solve()
t = num[d] - num[c];
int a = 0, b = c-1;
while(a < b) else if(num[a] + num[b] < t) else
}}
}printf("no solution\n");
}int main()
sort(num,num+n);
solve();
}return 0;
}
UVa10125 Sumsets 折半搜尋
題目大意 給出n個數字,求滿足a b c d最大的d 分析 先將等式變形為a b d c,然後找出所有可能的a b的值以及d c的值,接著就直接匹配就行了。include include include include include using namespace std const int ma...
10125 Sumsets(折半列舉 二分)
該題和挑戰上一道題很類似,如果列舉四個值的話,複雜度太高。那麼我們可以想辦法將複雜度分開。方法是 先用o n 2 預處理出來a b,然後列舉c和d,二分查詢ab中有沒有恰好等於d c的值。細節參見 includeusing namespace std typedef long long ll con...
高效演算法設計專項 UVa 10125
暴力列舉顯然會tle。lrj書裡介紹了中途相遇法,用map實現了一下,就是先用o n 2 建立乙個a b到乙個整數的對映,然後再用o n 2 列舉d c就可以在o n 2 複雜度下解決該問題了。需要注意的是a b c d不能重複,這裡我用map 實現以判重。只不過具體 比較醜 include inc...