标签:
http://community.topcoder.com/stat?c=problem_statement&pm=13628&rd=16278
标程是BFS,我用DFS,都可解。
这里复杂的把pair写了hash函数,其实直接用个矩阵来存bool就可以了。
#include <vector>
#include <algorithm>
#include <unordered_set>
#include <utility>
using namespace std;
struct pairhash {
public:
template <typename T, typename U>
std::size_t operator()(const std::pair<T, U> &x) const
{
return std::hash<T>()(x.first) * 37 ^ std::hash<U>()(x.second);
}
};
class TheGridDivTwo {
public:
unordered_set<pair<int, int>, pairhash> visited;
unordered_set<pair<int, int>, pairhash> block;
int find(vector <int> x, vector <int> y, int k) {
for (int i = 0; i < x.size(); i++) {
block.insert(make_pair(x[i], y[i]));
}
int result = 0;
pair<int, int> start = make_pair(0, 0);
findRe(result, start, k, 0);
return result;
}
void findRe(int &result, pair<int, int> &p, int k, int step) {
visited.insert(p);
if (step == k) {
result = max(result, p.first);
} else {
int dx[4] = {1, 0, 0, -1};
int dy[4] = {0, 1, -1, 0};
for (int i = 0; i < 4; i++) {
pair<int, int> tmp = make_pair(p.first + dx[i], p.second + dy[i]);
if (tmp.first + k - step > result && valid(tmp)) {
findRe(result, tmp, k, step + 1);
}
}
}
visited.erase(p);
}
bool valid(pair<int, int> &p) {
if (block.find(p) != block.end() || visited.find(p) != visited.end()) {
return false;
}
return true;
}
};
标签:
原文地址:http://www.cnblogs.com/lautsie/p/4245242.html