Cod sursa(job #1741385)

Utilizator Bulgaru_Robert_Razvan_323CBBulgaru Robert Razvan Bulgaru_Robert_Razvan_323CB Data 13 august 2016 19:51:25
Problema Numarare triunghiuri Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.49 kb
#include <cstdio>
#include <algorithm>
using namespace std;
int nr=0,heap[805];
int father(int nod){
    return nod / 2;
}
int left_son(int nod){
    return 2 * nod;
}
int right_son(int nod){
    return 2 * nod + 1;
}
void sift(int n, int k){
    int son;
    do{
        son = 0;
        if (left_son(k) <= n){
            son = left_son(k);
            if (right_son(k) <= n && heap[right_son(k)] > heap[left_son(k)])
                son = right_son(k);
            if (heap[son] <= heap[k])
                son = 0;
        }
        if (son){
            swap(heap[k], heap[son]);
            k = son;
        }
    }while(son);
}
void build_heap(int n){
    int i;
    for (i = n / 2; i >= 1; i --)
        sift(n, i);
}
void heap_sort(int n){
    int i;
    build_heap(n);
    for (i = n; i >= 2; i --){
        swap(heap[1], heap[i]);
        sift(i - 1, 1);
    }
}
void bs(int st, int dr, int val){
    int med, last = 0;
    while (st <= dr){
        med = (st + dr) >> 1;
        if (heap[med] < val){
           nr++;
            st = med + 1;
        }
        else{
            dr = med - 1;
        }
    }
    //return last;
}
int main(){
    freopen("nrtri.in", "r", stdin);
    freopen("nrtri.out", "w", stdout);
    int n, i, i1, i2, k = 0;
    scanf("%d", &n);
    for (i = 1; i <= n; i ++)
        scanf("%d", &heap[i]);
    heap_sort(n);
    for (i1 = 1; i1 <= n - 2; i1 ++)
        for (i2 = i1 + 1; i2 <= n - 1; i2 ++)
            bs(i2, n, heap[i2] + heap[i1]);
    printf("%d\n", nr-1);
    return 0;
}