fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. vector< char > topo;
  5. vector< vector<int> > adj(26);
  6. vector<bool> vis(26,true);
  7. void toposort(int i)
  8. {
  9. vis[i]=true;
  10. for(int j=0;j<adj[i].size();j++)
  11. {
  12. if(!vis[adj[i][j]])
  13. toposort(adj[i][j]);
  14. }
  15. topo.push_back(i+'a');
  16. }
  17. int main()
  18. {
  19. int n,i;
  20. cin>>n;
  21. vector<string> v;
  22. string s;
  23. while(n--)
  24. {
  25. cin>>s;
  26. v.push_back(s);
  27. }
  28. for(i=0;i<v.size();i++)
  29. {
  30. for(int j=0;j<v[i].size();j++)
  31. vis[v[i][j]-'a']=false;
  32. }
  33.  
  34. int len=v.size();
  35. for(i=0;i<len-1;i++)
  36. {
  37. int l1=v[i].size(),a;
  38. int l2=v[i+1].size();
  39. for(a=0;a<l1 && a<l2;a++)
  40. {
  41. if(v[i][a]!=v[i+1][a])
  42. {
  43. adj[v[i][a]-'a'].push_back(v[i+1][a]-'a');
  44. //cout<<v[i][a]-'a'<<' '<<v[i+1][a]-'a'<<endl;
  45. break;
  46. }
  47.  
  48. }
  49. }
  50.  
  51. for(i=0;i<26;i++)
  52. {
  53. if(!vis[i])
  54. {
  55. toposort(i);
  56. }
  57. }
  58.  
  59. n=topo.size();
  60. for(i=n-1;i>=0;i--)
  61. cout<<topo[i]<<endl;
  62. return 0;
  63. }
  64.  
Success #stdin #stdout 0s 15248KB
stdin
6
aaabc
aaade
bacd
cde
cda
cca
stdout
e
a
b
d
c