Advertisement
Guest User

Untitled

a guest
Feb 10th, 2025
52
0
243 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.40 KB | Source Code | 0 0
  1. void part1(std::vector<int> dm)
  2. {
  3.     Timer t;
  4.  
  5.     long long unsigned int result = 0;
  6.     int i = 0,j,id_first = 0, id_last;
  7.     j = (dm.size() % 2) ? dm.size() - 1 : dm.size() - 2;
  8.     id_last = j / 2;
  9.     // An individual file/empty space is different from file/empty block. Files in same block have same id.
  10.     // i is the position of individual file/empty space
  11.     // j is the position of file block starting from the end (decrements by 2 to keep pointing to file block)
  12.     // id_first and id_last is the ids of files blocks.
  13.  
  14.     for(int pos = 0; pos < dm.size(); ++pos)
  15.     {
  16.         if( pos % 2 == 0) // even position i.e it is file block
  17.         {
  18.             for(int k = 0; k < dm[pos]; ++k)  // for files in block at pos
  19.             {
  20.                 result += (id_first*i);
  21.                 ++i;
  22.             }
  23.             ++id_first;
  24.         }
  25.         else // odd position i.e. empty block
  26.         {
  27.             for(int k = 0; k < dm[pos]; ++k) // for empty spaces in block at pos
  28.             {
  29.                 while(dm[j] == 0 && j > pos) //  shift j left until
  30.                 {
  31.                     j-=2;
  32.                     --id_last;
  33.                 }
  34.                 if(j<pos) break;
  35.  
  36.                 --dm[j];
  37.                 result += (id_last*i);
  38.                 ++i;
  39.             }
  40.         }
  41.         if(j<pos) break;
  42.     }
  43.     cout << "Part 1: " << result << endl;
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement