Max_Leb

Вася и Суперкомпьютер

Jun 15th, 2022
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.14 KB | None | 0 0
  1. # Вася и Суперкомпьютер
  2.  
  3. #include <iostream>
  4. #include <fstream>
  5.  
  6. void swap(int array[], int i, int j) {
  7.     int tmp = array[i];
  8.     array[i] = array[j];
  9.     array[j] = tmp;
  10. }
  11.  
  12. void sort(int array[], int len) {
  13.     int needIteration = 1;
  14.     while (needIteration) {
  15.         needIteration = 0;
  16.         for (int i = 1; i < len; ++i) {
  17.             if (array[i] > array[i-1]) {
  18.                 swap(array, i, i - 1);
  19.                 needIteration = 1;
  20.             }
  21.         }
  22.         len--;
  23.     }
  24. }
  25.  
  26. int main() {
  27.     std::ifstream fin("input.txt");
  28.     std::ofstream fout("output.txt");
  29.     int N, length;
  30.     fin >> N;
  31.     int one[N], zero[N];
  32.     for (int i = 0; i < N; ++i) {
  33.         one[i] = 0;
  34.         zero[i] = 0;
  35.     }
  36.     int one_index = 0, zero_index = 0;
  37.     int only_one = 0, only_zero = 0;
  38.     std::string line;
  39.     for (int i = 0; i < N; ++i) {
  40.         fin >> length;
  41.         fin >> line;
  42.         if (line[0] == '1' && line[length - 1] == '0')
  43.             one[one_index++] = length;
  44.         else if (line[0] == '0' && line[length - 1] == '1')
  45.             zero[zero_index++] = length;
  46.         else if (line[0] == '1' && line[length - 1] == '1')
  47.             only_one += length;
  48.         else
  49.             only_zero += length;
  50.     }
  51.     int result = 0;
  52.     if (one_index == 0 && zero_index == 0) {
  53.         result = only_one > only_zero ? only_one : only_zero;
  54.         fout << result;
  55.         return 0;
  56.     }
  57.     result += only_one + only_zero;
  58.  
  59.     sort(one, one_index);
  60.     sort(zero, zero_index);
  61.  
  62.     if (one_index > zero_index) {
  63.         int ind = 0;
  64.         while (zero_index > 0) {
  65.             result += one[ind] + zero[ind++];
  66.             zero_index--;
  67.         }
  68.         result += one[ind];
  69.     }
  70.     else if (zero_index > one_index) {
  71.         int ind = 0;
  72.         while (one_index > 0) {
  73.             result += zero[ind] + one[ind++];
  74.             one_index--;
  75.         }
  76.         result += zero[ind];
  77.     }
  78.     else {
  79.         for (int i = 0; i < one_index; ++i)
  80.             result += one[i] + zero[i];
  81.     }
  82.     fout << result;
  83.     fin.close();
  84.     fout.close();
  85.     return 0;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment