Optimiser F7 par tri et parcours à deux pointeurs

This commit is contained in:
rabot
2026-10-21 11:15:03 +02:00
parent 1c7970b554
commit 02fcd4b443
3 changed files with 94 additions and 5 deletions
+45 -5
View File
@@ -186,13 +186,53 @@ const Transaction *rechercher_par_id(const Transaction *const *index_ids, int n,
}
/* F7 : nombre de paires de transactions de montants opposés (a + b = 0) */
long nb_paires_opposees(const Transaction *t, int n)
static long compter_paires_triees(const Transaction *t, int 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)
nb++;
int gauche = 0;
int droite = n - 1;
while (gauche < droite) {
long somme = t[gauche].montant + t[droite].montant;
if (somme < 0) {
gauche++;
} else if (somme > 0) {
droite--;
} else if (t[gauche].montant == 0) {
long taille = droite - gauche + 1;
nb += taille * (taille - 1) / 2;
break;
} else {
long nb_gauche = 1;
long nb_droite = 1;
while (gauche + 1 < droite && t[gauche + 1].montant == t[gauche].montant) {
gauche++;
nb_gauche++;
}
while (droite - 1 > gauche && t[droite - 1].montant == t[droite].montant) {
droite--;
nb_droite++;
}
nb += nb_gauche * nb_droite;
gauche++;
droite--;
}
}
return nb;
}
long nb_paires_opposees(const Transaction *t, int n)
{
if (n < 2)
return 0;
Transaction *copie = malloc((size_t)n * sizeof(*copie));
if (copie == NULL) {
perror("Allocation de la copie des transactions");
exit(EXIT_FAILURE);
}
memcpy(copie, t, (size_t)n * sizeof(*copie));
trier_par_montant(copie, n);
long nb = compter_paires_triees(copie, n);
free(copie);
return nb;
}