Pagini recente » Cod sursa (job #1921250) | Cod sursa (job #1921347) | Cod sursa (job #453241) | Rating Constantinescu Mihai-Vlad (jinx0044) | Cod sursa (job #2869199)
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data; // integer data
struct Node* next; // pointer to the next node
};
int nodesCount;
void push(struct Node** top, int x)
{
struct Node* node = NULL;
node = (struct Node*)malloc(sizeof(struct Node));
if (!node)
{
printf("Heap Overflow\n");
exit(-1);
}
node->data = x;
node->next = *top;
*top = node;
nodesCount += 1;
}
int isEmpty(struct Node* top) {
return top == NULL;
}
int peek(struct Node* top)
{
if (!isEmpty(top)) {
return top->data;
}
else {
printf("The stack is empty\n");
exit(EXIT_FAILURE);
}
}
int pop(struct Node** top)
{
struct Node* node;
if (*top == NULL)
{
printf("Stack Underflow\n");
exit(EXIT_FAILURE);
}
int x = peek(*top);
node = *top;
*top = (*top)->next;
nodesCount -= 1;
free(node);
return x;
}
int size() {
return nodesCount;
}
int verificaT(int m,struct Node* top) {
int i, sum = 0, j = size(), o = 0, t = 0;
int a[100];
for (i = 0; i < j + o; i++) {
if (!isEmpty(top)) {
if (sum + peek(top) <= m) {
sum += peek(top);
a[o] = peek(top);
pop(&top);
o++;
if (isEmpty(top))
t++;
}
else {
t++;
sum = 0;
}
}
else
continue;
}
for (i = o - 1; i >= 0; i--) {
push(&top, a[i]);
}
return t;
}
int cautareBinara(int s, int d, int k, struct Node* top) {
int i;
int t = d, m;
for (i = 0; i <= t; i++) {
m = (s + d) / 2;
if (verificaT(m, top) < k)
d = m;
else if (verificaT(m, top) > k)
s = m;
else
return m;
}
}
int main(void) {
int N, K, V, d = 0, s = 0;
struct Node* top = NULL;
do {
scanf("%d %d", &N, &K); //nr de saltele
} while ((N < 1 || N > 16000) && (K < 1 || K > 16000));
for (int i = 0; i < N; i++) {
do {
scanf("%d", &V); //volumele saltelelor
} while (V < 1 || V > 16000);
push(&top, V);
d += V;
}
printf("%d", cautareBinara(s, d, K, top));
return 0;
}