999ms

B. Лиса и имена

Apr 8th, 2020
269
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.98 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using i32 = int;
  4. using ui32 = unsigned int;
  5. using i64 = long long;
  6. using ui64 = unsigned long long;
  7.  
  8.  
  9. const ui32 MSIZE = 26;
  10.  
  11. bool g[MSIZE][MSIZE];
  12. std::string arr[100];
  13. ui32 color[MSIZE];
  14.  
  15. bool CycleExists(ui32 from) {
  16.   color[from] = 1;
  17.   for (ui32 i = 0; i < MSIZE; i++) {
  18.     if (g[from][i]) {
  19.       if (color[i] == 1) return true;
  20.       if (CycleExists(i)) return true;
  21.     }
  22.   }
  23.   color[from] = 2;
  24.   return false;
  25. }
  26.  
  27. void TopsortDfs(ui32 from, std::vector<ui32>& result) {
  28.   color[from] = true;
  29.   for (ui32 i = 0; i < MSIZE; i++) {
  30.     if (g[from][i] == true and color[i] == false) {
  31.       TopsortDfs(i, result);
  32.     }
  33.   }
  34.   result.push_back(from);
  35. }
  36.  
  37. i32 main() {
  38.   ui32 n;
  39.   std::cin >> n;
  40.   for (ui32 i = 0; i < n; i++) {
  41.     std::cin >> arr[i];
  42.     for (ui32 j = 0; j < std::size(arr[i]); j++) {
  43.       arr[i][j] -= 'a';
  44.     }
  45.   }
  46.   bool alphabetExists = true;
  47.   for (ui32 i = 0; i + 1 < n; i++) {
  48.     ui32 minLength = std::min(std::size(arr[i]), std::size(arr[i + 1]));
  49.     bool cmp = false;
  50.     for (ui32 j = 0; j < minLength; j++) {
  51.       if (arr[i][j] != arr[i + 1][j]) {
  52.         g[arr[i][j]][arr[i + 1][j]] = true;
  53.         cmp = true;
  54.         break;
  55.       }
  56.     }
  57.     if (cmp == false and std::size(arr[i]) > std::size(arr[i + 1])) {
  58.       alphabetExists = false;
  59.       break;
  60.     }
  61.   }
  62.   for (ui32 i = 0; i < MSIZE; i++) {
  63.     if (color[i] == 0) {
  64.       if (CycleExists(i)) {
  65.         alphabetExists = false;
  66.         break;
  67.       }
  68.     }
  69.   }
  70.   if (alphabetExists == false) {
  71.     puts("Impossible");
  72.     return 0;
  73.   }
  74.   std::fill(color, color + MSIZE, 0); // equals to used
  75.   std::vector<ui32> alphabet;
  76.   for (ui32 i = 0; i < MSIZE; i++) {
  77.     if (color[i] == false) {
  78.       TopsortDfs(i, alphabet);
  79.     }
  80.   }
  81.   std::reverse(std::begin(alphabet), std::end(alphabet));
  82.   std::string answer(26, 'a');
  83.   for (ui32 i = 0; i < MSIZE; i++) {
  84.     answer[i] += alphabet[i];
  85.   }
  86.   puts(answer.c_str());
  87. }
Add Comment
Please, Sign In to add comment