Cod sursa(job #2062160)

Utilizator Teodor.mTeodor Marchitan Teodor.m Data 10 noiembrie 2017 01:12:43
Problema Numarare triunghiuri Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.82 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("nrtri.in");
ofstream gout("nrtri.out");

int a[850];
int n;

int cautare_binara(int a[], int st, int dr, int val)
{
	while(st < dr) {
		int mid = st + (dr - st) / 2;
		if(a[mid] <= val)
			st = mid + 1;
		else if(a[mid] > val) {
			dr = mid - 1;
		}
			else {
				return mid;
			}
	}
}
int main()
{
	fin >> n;

	for(int i = 1; i <= n; ++i) fin >> a[i];
	sort(a + 1, a + n + 1);
	for(int i = 1; i <= n; ++i) gout << a[i] << " ";
	gout << '\n';

	int ans = 0;
	for(int i  = 1; i < n; ++i) {
		for(int j = i + 1; j <= n; ++j) {
			int suma = a[i] + a[j];
			int pos = cautare_binara(a, j + 1, n, suma);
			if(a[pos] == suma) {
				ans += pos - j;
			}

			else {
				ans += pos - j - 1;
			}

		}
	}

	gout << ans;
	return 0;
}