USACO 1.3 Combation Lock

Reduce to a search problem, pay attion to the search space. Code can be further optimized.


#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
#include <string>
#include <cctype>
#include <algorithm>
#include <tuple>
#include <set>

using namespace std;

int wrap(int num, int N) {
if (num <= 0) {
return num + N;
}
if (num > N) {
return num - N;
}
return num;
}

vector<int> getCandidate(int num, int N) {
vector<int> ret;
int range;
if (N == 1) {
range = 0;
} else if (N == 2) {
range = 1;
} else {
range = 2;
}
cout << -range << endl;
for (int i = -range; i <= range; ++i) {
ret.emplace_back(wrap(num + i, N));
}
return ret;
}

int main() {
ifstream fin("combo.in");
ofstream fout("combo.out");

int N;
vector<int> lock(3, 0), master(3, 0);
vector<vector<int>> a, b;
fin >> N;

for (int i = 0; i < 3; ++i) {
fin >> lock[i];
a.emplace_back(getCandidate(lock[i], N));
}

for (int i = 0; i < 3; ++i) {
fin >> master[i];
b.emplace_back(getCandidate(master[i], N));
}

set<tuple<int, int, int>> s;
for (int i = 0; i < a[0].size(); ++i) {
for (int j = 0; j < a[1].size(); ++j) {
for (int k = 0; k < a[2].size(); ++k) {
s.insert(make_tuple(a[0][i], a[1][j], a[2][k]));
}
}
}

for (int i = 0; i < b[0].size(); ++i) {
for (int j = 0; j < b[1].size(); ++j) {
for (int k = 0; k < b[2].size(); ++k) {
s.insert(make_tuple(b[0][i], b[1][j], b[2][k]));
}
}
}

fout << s.size() << endl;

for (auto &item : s) {
cout << get<0>(item) << ","
<< get<1>(item) << ","
<< get<2>(item) << " ";
}
cout << endl;

return 0;
}