This commit is contained in:
Nataliia Kobryn 2025-12-03 01:27:34 +01:00
parent aa132d9009
commit 19f7061562
2 changed files with 120 additions and 0 deletions

120
a2/program.c Normal file
View File

@ -0,0 +1,120 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
struct person{
char meno[100];
int vek;
};
void add_person(struct person** heap,int hsz, const char* meno, int vek ){
struct person* item = calloc(1,sizeof(struct person));
item->vek = vek;
strcpy(item->meno,meno);
// Uložíme na koniec
heap[hsz] = item;
// Pozrieme na jeho rodiča
int p = (hsz -1) / 2;
int i = hsz;
// Pokiaľ rodič existuje a jeho hodnota je väčšia
while(p >= 0 && heap[p]->vek > heap[i]->vek){
// Vymeníme ich hodnoty
struct person* this = heap[i];
heap[i] = heap[p];
heap[p] = this;
// Pokračujeme ďalším rodičom
i = p;
p = (p - 1) / 2;
}
}
void heapify(struct person** heap, int hsz,int i){
struct person* this = heap[i];
int left_index = (2*i) + 1;
int right_index = (2*i) + 2;
// Zistíme kde sa nachádza minimum
int m = i;
if (left_index < hsz && heap[left_index]->vek < this->vek){
m = left_index;
}
if (right_index < hsz && heap[right_index]->vek < this->vek){
m = right_index;
}
if (m != i){
heap[i] = heap[m];
heap[m] = this;
heapify(heap,hsz,m);
}
}
int is_kopa(struct person** kopa, int n) {
for (int i = 0; i < n; i++) {
int l = 2*i + 1;
int r = 2*i + 2;
if (l < n && kopa[l]->vek < kopa[i]->vek) return 0;
if (r < n && kopa[r]->vek < kopa[i]->vek) return 0;
}
return 1;
}
void print_tree(struct person** heap, int n, int i, int level) {
if (i >= n) return;
for (int k = 0; k < level; k++)
printf(" ");
printf("%d\n", heap[i]->vek);
print_tree(heap, n, 2*i + 1, level + 1);
print_tree(heap, n, 2*i + 2, level + 1);
}
int main() {
char line[1000];
struct person* heap[500];
memset(heap, 0, sizeof(heap));
int count = 0;
fgets(line, sizeof(line), stdin);
char* p = line;
while (*p) {
while (isspace(*p)) p++;
if (*p == '\0') break;
int value = strtol(p,&p,10);
heap[count] = malloc(sizeof(struct person));
heap[count]->vek = value;
strcpy(heap[count]->meno, "");
count++;
}
if (!is_kopa(heap, count)) {
printf("Nie je kopa.\n");
return 0;
}
while (*p) {
while (isspace(*p)) p++;
if (*p == '\0') break;
int value = strtol(p, &p, 10);
add_person(heap, count, "", value);
count++;
}
// výpis
printf("Je to taka kopa:\n");
print_tree(heap, count, 0, 0);
return 0;
}

BIN
a2/test Executable file

Binary file not shown.