Kings
+---+A+---+ +---->A+---+
| | | |
| | | |
v v + v
B <------+C C<--------+Dvector<char> king_vertices(vector<char> &ar1, vector<char> &ar2) {
map<char, vector<char>> list;
unordered_set<char> check_list;
unordered_set<char> check_list_copy;
for (int i = 0; i < ar1.size(); i++) {
auto &found = list.find(ar1.at(i));
if (found == list.end()) {
vector<char> connections;
connections.push_back(ar2.at(i));
list.insert({ {ar1.at(i)}, {connections} });
}
else {
found->second.push_back(ar2.at(i));
}
// automatically maintains unique elements
check_list.insert(ar1.at(i));
check_list.insert(ar2.at(i));
}
check_list_copy = check_list;
vector<char> kings;
for (auto &i : list) {
for (auto &j : i.second) {
check_list.erase(j);
//second step
auto &found3 = list.find(j);
if (found3 != list.end()) {
for (int k = 0; k < list.find(j)->second.size(); k++) {
check_list.erase(list.find(j)->second.at(k));
}
}
}
// remainder is itself
if (check_list.size() <= 1) {
if (check_list.size() == 0 || check_list.find(i.first) != check_list.end()) {
kings.push_back(i.first);
check_list = check_list_copy;
}
}
check_list = check_list_copy;
}
sort(kings.begin(), kings.end());
return kings;
}
int main() {
vector<char> one = { 'A', 'A', 'B' };
vector<char> two = { 'B', 'C', 'C' };
print(king_vertices(one, two));
one = { 'A', 'A', 'A', 'C' };
two = { 'E', 'B', 'C', 'D' };
print(king_vertices(one, two));
one = { 'A', 'A', 'A','B', 'D', 'D', 'D', 'C' };
two = { 'B', 'C', 'E','A', 'B', 'C', 'E', 'D' };
print(king_vertices(one, two));
}Last updated