Tina love cookies
#include <iostream>
using namespace std;
// Node structure for Linked List
struct Node {
int data;
Node* next;
};
// Function to insert a node in sorted order
void insertSorted(Node*& head, int value) {
Node* newNode = new Node();
newNode->data = value;
newNode->next = NULL;
if (head == NULL || value < head->data) {
newNode->next = head;
head = newNode;
return;
}
Node* temp = head;
while (temp->next != NULL && temp->next->data < value)
temp = temp->next;
newNode->next = temp->next;
temp->next = newNode;
}
// Function to remove and return the smallest element (head)
int removeMin(Node*& head) {
if (head == NULL) return -1;
int val = head->data;
Node* temp = head;
head = head->next;
delete temp;
return val;
}
// Function to print linked list (for understanding)
void printList(Node* head) {
Node* temp = head;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
// ---------------- MAIN LOGIC ----------------
int main() {
int n, k;
cout << "Enter number of cookies: ";
cin >> n;
Node* head = NULL;
cout << "Enter sweetness of each cookie:\n";
for (int i = 0; i < n; i++) {
int val;
cin >> val;
insertSorted(head, val); // insert in sorted order
}
cout << "Enter minimum required sweetness (k): ";
cin >> k;
int operations = 0;
while (head != NULL && head->data < k) {
if (head->next == NULL) {
cout << "Not possible to reach required sweetness!\n";
return 0;
}
// Take two least sweet cookies
int first = removeMin(head);
int second = removeMin(head);
// Combine them
int newSweetness = first + 2 * second;
insertSorted(head, newSweetness);
operations++;
}
cout << "\nAll cookies now have sweetness >= " << k << endl;
cout << "Minimum operations required: " << operations << endl;
cout << "\nTime Complexity: O(n log n)\nSpace Complexity: O(n)\n";
return 0;
}
Editor is loading...
Leave a Comment