1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 |
#include <iostream> #include <string> #include <sstream> #include <fstream> #include <queue> #include <algorithm> #include <cstring> #include <set> using namespace std; int noOfelement; int mp[26]; string str,str1,str2; string output[2000]; int kk; bool gr[27][27]; stringstream ss; int elements[26]; set<string> SET; //ofstream out; bool check(int elemnt,bool visit[]) { for(int i=0;i<26;i++) { if(gr[i][elemnt] && mp[i]!=-1 && visit[mp[i]]==0) return 0; } return 1; } int recur(bool used[],string s) { if(s.size()==noOfelement) { output[kk++]=s; return 0; } for(int i=0;i<noOfelement;i++) { if(used[i]==0 && check(elements[i],used)==1) { used[i]=1; s.append(1u,char(elements[i]+'A')); recur(used,s); s.erase(s.begin()+(s.size()-1)); used[i]=0; } } return 0; } void topologicalsort() { bool visit[noOfelement]; string res = ""; for(int i=0;i<noOfelement;i++) { visit[i]=false; } for(int i=0;i<noOfelement;i++) { if(visit[i]==0 && check(elements[i],visit)==1) { visit[i]=1; res.append(1u,char(elements[i]+'A')); recur(visit,res); res.erase(res.begin()+(res.size()-1)); visit[i]=0; } } } bool cmp(string s1,string s2) { int sum = 0; for(int i=0;i<s1.size();i++) { if(s1[i]!=s2[i]) { return (s1[i]<s2[i]); } } } int main() { int cnt = 0,t; int a,b; stringstream ss; bool first = 0; char c; getline(cin,str); ss<<str; ss>>t; ss.clear(); getline(cin,str); while(t--) { getline(cin,str1); getline(cin,str2); if(t) getline(cin,str); ss.clear(); ss<<str1; for(int i=0;i<26;i++) { mp[i]=-1; elements[i]=0; for(int j=0;j<26;j++) gr[i][j]=0; } noOfelement=0; while(ss>>c) { mp[c-'A']=noOfelement; elements[noOfelement]=c-'A'; noOfelement++; } ss.clear(); ss<<str2; bool f = 0; char tmp[200]; int char_cnt = 0; while(ss>>c) { if(c>='A' && c<='Z') tmp[char_cnt++]=c; } for(int i=0;i<char_cnt;i++) { if(i%2) { b = tmp[i]-'A'; gr[a][b]=1; } else a = tmp[i]-'A'; } kk=0; topologicalsort(); sort(output+0,output+kk,cmp); for(int ii=0;ii<kk;ii++) { for(int jj=0;jj<output[ii].size();jj++) cout<<output[ii][jj]<<(jj!=output[ii].size()-1?" ":"\n"); } if(kk==0) cout<<"NO\n"; if(t) cout<<"\n"; } //out.close(); return 0; } |