CF C. Fox And Names(拓扑排序)

题意:给出n个字符串,求是否存在一种新的字母大小顺序,使这n个字符串满足这种顺序。

思路:注意每相邻两个串相比较时,从头到尾,只要比较到相同位置,字母不同,就结束了,不要继续向后比较了。

 1 #include<iostream>

 2 #include<cstdio>

 3 #include<cstdlib>

 4 #include<cstring>

 5 #include<string>

 6 #include<queue>

 7 #include<algorithm>

 8 #include<map>

 9 #include<iomanip>

10 #include<climits>

11 #include<string.h>

12 #include<numeric>

13 #include<cmath>

14 #include<stdlib.h>

15 #include<vector>

16 #include<stack>

17 #include<set>

18 #define FOR(x, b, e)  for(int x=b;x<=(e);x++)

19 #define REP(x, n)     for(int x=0;x<(n);x++)

20 #define INF 1e7

21 #define MAXN 100010

22 #define maxn 1000010

23 #define Mod 1000007

24 #define N 110

25 using namespace std;

26 typedef long long LL;

27 

28 int n;

29 string s[N];

30 int G[N][N];

31 int ind[N];

32 bool flag;

33 string ans;

34 

35 bool gao()

36 {

37     queue<int> q;

38     for (int i = 0;i < 26;++ i) 

39         if (ind[i] == 0) {

40             q.push(i);

41             ans += (char)(i + 'a');

42         }

43     while (!q.empty()) {

44         int t = q.front();

45         q.pop();

46         for (int i = 0;i < 26;++ i)

47             if (G[t][i]) {

48                 if (--ind[i] == 0) {

49                     q.push(i);    

50                     ans += (char)(i + 'a');

51                 }

52             }

53     }

54     if (ans.length() == 26) return 1;

55     return 0;

56 }

57 

58 int main()

59 {

60     cin >> n;

61     for (int i = 1;i <= n;++ i)

62         cin >> s[i];

63     for (int i = 2;i <= n;++ i) {

64         int len1 = s[i - 1].length();

65         int len2 = s[i].length();

66         bool ok = false;

67         for (int j = 0;j < len1 && j < len2 && !ok;++ j) {

68             if (s[i-1][j] != s[i][j]) {

69                 ok = true;

70                 if (G[s[i-1][j] - 'a'][s[i][j] - 'a'] == 0) {

71                     G[s[i-1][j] - 'a'][s[i][j] - 'a'] = 1;

72                     ind[s[i][j] - 'a']++;

73                 }

74             }

75         }

76         if (!ok && len1 > len2) {

77             puts("Impossible");

78             return 0;

79         }

80     }

81     //cout << "ok" << endl;

82     int res = gao();

83     if (res == 0) puts("Impossible");

84     else cout << ans << endl;

85     return 0;

86 }

 

你可能感兴趣的:(name)