Problem Link
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
long arr[2002];
int binarySearch(int start, int end, int x){
while(end > start){
int mid = (start + end) / 2;
if(arr[mid] > x){
end = mid;
}
else{
start = mid + 1;
}
}
return end;
}
int main(){
int n, b;
long result = 0;
while(true){
cin >> n;
if(n == 0)
break;
for(int i = 0; i < n; i++){
cin >> arr[i];
}
sort(arr, arr + n);
result = 0;
for(int i = 0; i < n; i++){
for(int j = i + 1; j < n; j++){
if(arr[i] + arr[j] < arr[n - 1]){
/* Find the first element which is greater than sum of two element */
b = binarySearch(i, n - 1, arr[i] + arr[j]);
result += (n - b);
}
}
}
cout << result << endl;
}
return 0;
}
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
long arr[2002];
int binarySearch(int start, int end, int x){
while(end > start){
int mid = (start + end) / 2;
if(arr[mid] > x){
end = mid;
}
else{
start = mid + 1;
}
}
return end;
}
int main(){
int n, b;
long result = 0;
while(true){
cin >> n;
if(n == 0)
break;
for(int i = 0; i < n; i++){
cin >> arr[i];
}
sort(arr, arr + n);
result = 0;
for(int i = 0; i < n; i++){
for(int j = i + 1; j < n; j++){
if(arr[i] + arr[j] < arr[n - 1]){
/* Find the first element which is greater than sum of two element */
b = binarySearch(i, n - 1, arr[i] + arr[j]);
result += (n - b);
}
}
}
cout << result << endl;
}
return 0;
}
Comments
Post a Comment