diff --git a/banque b/banque index b24d472..55060bc 100755 Binary files a/banque and b/banque differ diff --git a/banque.c b/banque.c index acc2d13..42dc709 100644 --- a/banque.c +++ b/banque.c @@ -162,13 +162,45 @@ const Transaction *rechercher_par_id(const Transaction *t, int n, int id) } /* F7 : nombre de paires de transactions de montants opposés (a + b = 0) */ + + +static int cmp_long(const void *a, const void *b) +{ + long x = *(const long *)a; + long y = *(const long *)b; + return (x > y) - (x < y); +} + long nb_paires_opposees(const Transaction *t, int n) { + /* 1. Copier et trier les montants : O(n log n) */ + long *m = malloc(n * sizeof(long)); + for (int i = 0; i < n; i++) { + m[i] = t[i].montant; + } + qsort(m, n, sizeof(long), cmp_long); + + /* 2. Deux pointeurs : O(n) au lieu de O(n²) */ long nb = 0; - for (int i = 0; i < n; i++) - for (int j = i + 1; j < n; j++) - if (t[i].montant + t[j].montant == 0) + int g = 0, d = n - 1; + + while (g < d) { + long somme = m[g] + m[d]; + + if (somme < 0) { + g++; + } else if (somme > 0) { + d--; + } else { + /* somme == 0 : on compte tous les m[d] identiques en face de m[g] */ + for (int k = d; k > g && m[k] == m[d]; k--) { nb++; + } + g++; /* Puis on passe simplement au m[g] suivant ! */ + } + } + + free(m); return nb; }