c_cpp 跳蛙
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 跳蛙相关的知识,希望对你有一定的参考价值。
// The frog start at position -1, the river starts at position 0, the frog must go to position river size (path) or bigger
// Compile with c++11, e.g. in clang++: clang++ frog.cpp -std=c++11
#include <vector>
#include <iostream>
#include <tuple>
typedef std::vector<int> Path;
typedef std::vector<std::tuple<int, int> > Visited;
bool walk(const int pos, const int speed, const Path& path, Visited& visited, Visited& walking);
static int ts = 0;
int main() {
Path path = {0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1};
Visited visited;
int pos = -1;
int speed = 0;
Visited walking;
if (walk(pos, speed , path, visited, walking)) {
std::cerr << "#ops: " << ts << std::endl;
std::cerr << "***** " << walking.size() << " ***** " << std::endl;
for (auto w: walking) {
std::cerr << std::get<0>(w) << " " << std::get<1>(w) << std::endl;
}
return 0;
}
return 1;
}
bool walk(const int pos, const int speed, const Path& path, Visited& visited, Visited& walking) {
ts++;
if (std::find(visited.begin(), visited.end(), std::make_tuple(pos, speed)) != visited.end()) {
return false;
}
visited.emplace_back(pos, speed);
// Crossed the river
if (pos >= (signed) (path.size())) {
walking.push_back(std::make_tuple(pos, speed));
return true;
}
// Is on some block?
if (pos >= 0 && !path[pos]) {
return false;
}
// Too far from the river
if (pos <= (-10 * (signed) path.size())) {
return false;
}
std::vector<Visited> walkings;
Visited walking1;
if (walk(pos + (speed + 1), speed + 1, path, visited, walking1)) {
walkings.push_back(walking1);
}
Visited walking2;
if (walk(pos + speed, speed, path, visited, walking2)) {
walkings.push_back(walking2);
}
Visited walking3;
if (walk(pos + (speed - 1), speed - 1, path, visited, walking3)) {
walkings.push_back(walking3);
}
if (walkings.empty()) {
return false;
}
std::sort(walkings.begin(), walkings.end(), [](Visited& a, Visited& b) {
return a.size() < b.size();
});
walking = walkings[0];
walking.push_back(std::make_tuple(pos, speed));
return true;
}
以上是关于c_cpp 跳蛙的主要内容,如果未能解决你的问题,请参考以下文章