-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path872-Ordering.cpp
72 lines (70 loc) · 1.67 KB
/
872-Ordering.cpp
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
#include<bits/stdc++.h>
using namespace std;
vector<char> vars;
unordered_set<char> used;
unordered_map<char,int> indegree;
unordered_map<char,unordered_set<char>> graph;
void backtrack(string& cur,vector<string>& res){
if(cur.size() == vars.size()){
res.push_back(cur);
return;
}
for(auto& var : vars){
if(used.count(var) || indegree[var]!=0) continue;
cur += var;
used.insert(var);
for(auto& neighbor : graph[var]){
indegree[neighbor]--;
}
backtrack(cur,res);
cur.pop_back();
used.erase(var);
for(auto& neighbor : graph[var]){
indegree[neighbor]++;
}
}
}
int main()
{
int t;
string in;
cin >> t;
cin.ignore();
while(t--){
cin.ignore();
vars.clear();
used.clear();
indegree.clear();
graph.clear();
getline(cin,in);
istringstream iss(in);
while(iss >> in){
vars.push_back(in[0]);
}
getline(cin,in);
iss.clear();
iss.str(in);
while(iss >> in){
char a = in[0];
char b = in[2];
if(!graph[a].count(b)){
indegree[b]++;
graph[a].insert(b);
}
}
vector<string> res;
string cur = "";
backtrack(cur,res);
sort(res.begin(),res.end());
if(res.empty())
printf("NO\n");
else{
for(auto& r : res){
printf("%c",r[0]);
for(int i=1;i<r.size();i++) printf(" %c",r[i]);
printf("\n");
}
}
if(t) printf("\n");
}
}