Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using i32 = int;
- using ui32 = unsigned int;
- using i64 = long long;
- using ui64 = unsigned long long;
- const ui32 MSIZE = 26;
- bool g[MSIZE][MSIZE];
- std::string arr[100];
- ui32 color[MSIZE];
- bool CycleExists(ui32 from) {
- color[from] = 1;
- for (ui32 i = 0; i < MSIZE; i++) {
- if (g[from][i]) {
- if (color[i] == 1) return true;
- if (CycleExists(i)) return true;
- }
- }
- color[from] = 2;
- return false;
- }
- void TopsortDfs(ui32 from, std::vector<ui32>& result) {
- color[from] = true;
- for (ui32 i = 0; i < MSIZE; i++) {
- if (g[from][i] == true and color[i] == false) {
- TopsortDfs(i, result);
- }
- }
- result.push_back(from);
- }
- i32 main() {
- ui32 n;
- std::cin >> n;
- for (ui32 i = 0; i < n; i++) {
- std::cin >> arr[i];
- for (ui32 j = 0; j < std::size(arr[i]); j++) {
- arr[i][j] -= 'a';
- }
- }
- bool alphabetExists = true;
- for (ui32 i = 0; i + 1 < n; i++) {
- ui32 minLength = std::min(std::size(arr[i]), std::size(arr[i + 1]));
- bool cmp = false;
- for (ui32 j = 0; j < minLength; j++) {
- if (arr[i][j] != arr[i + 1][j]) {
- g[arr[i][j]][arr[i + 1][j]] = true;
- cmp = true;
- break;
- }
- }
- if (cmp == false and std::size(arr[i]) > std::size(arr[i + 1])) {
- alphabetExists = false;
- break;
- }
- }
- for (ui32 i = 0; i < MSIZE; i++) {
- if (color[i] == 0) {
- if (CycleExists(i)) {
- alphabetExists = false;
- break;
- }
- }
- }
- if (alphabetExists == false) {
- puts("Impossible");
- return 0;
- }
- std::fill(color, color + MSIZE, 0); // equals to used
- std::vector<ui32> alphabet;
- for (ui32 i = 0; i < MSIZE; i++) {
- if (color[i] == false) {
- TopsortDfs(i, alphabet);
- }
- }
- std::reverse(std::begin(alphabet), std::end(alphabet));
- std::string answer(26, 'a');
- for (ui32 i = 0; i < MSIZE; i++) {
- answer[i] += alphabet[i];
- }
- puts(answer.c_str());
- }
Add Comment
Please, Sign In to add comment