Max_Leb

Ближайшее число

Jun 15th, 2022
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. # Ближайшее число
  2.  
  3. #include <iostream>
  4. #include <fstream>
  5.  
  6. struct Node {
  7.     int value;
  8.     Node* next;
  9. };
  10.  
  11. void push(Node** head, int value) {
  12.     Node* new_node = new Node[sizeof(Node)];
  13.     new_node->next = *head;
  14.     new_node->value = value;
  15.     *head = new_node;
  16.  
  17. }
  18.  
  19. void pop(Node** head) {
  20.     if ((*head) != nullptr)
  21.         *head = (*head)->next;
  22. }
  23.  
  24. int top(Node* head) {
  25.     if (head != nullptr)
  26.         return head->value;
  27. }
  28.  
  29. int isEmpty(Node** head){
  30.     if (*head == nullptr)
  31.         return 1;
  32.     return 0;
  33. }
  34.  
  35. int main() {
  36.     std::ifstream fin("input.txt");
  37.     std::ofstream fout("output.txt");
  38.     int N;
  39.     fin >> N;
  40.     int a[N];
  41.     for (int i = 0; i < N; ++i){
  42.         fin >> a[i];
  43.     }
  44.  
  45.     Node *stack = nullptr;
  46.     Node *index = nullptr;
  47.  
  48.     push(&stack, a[0]);
  49.     push(&index, 0);
  50.  
  51.     for (int i = 1; i < N; ++i){
  52.         while (!isEmpty(&stack) && top(stack) < a[i]){
  53.             a[top(index)] = a[i];
  54.             pop(&stack);
  55.             pop(&index);
  56.         }
  57.         push(&stack, a[i]);
  58.         push(&index, i);
  59.  
  60.     }
  61.     for (int i = 0; i < N; ++i)
  62.         fout << a[i] << " ";
  63.  
  64.     fin.close();
  65.     fout.close();
  66.  
  67.     return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment