#include "garden.h"
#include "gardenlib.h"
#include <vector>
#include <deque>
#include <set>
using namespace std;
void count_routes(int N, int M, int P, int R[][2], int Q, int G[]) {
// Build adjacency lists, but only keep up to 2 edges per node
vector<vector<int>> node_edges(N + 1);
for (int idx = 0; idx < M; ++idx) {
int i = R[idx][0];
int j = R[idx][1];
if (node_edges[i].size() < 2) {
node_edges[i].push_back(j);
}
if (node_edges[j].size() < 2) {
node_edges[j].push_back(i);
}
}
// Walk function: choose the neighbor that's not the one we came from
auto do_walk = [&](int walk, int prev_walk) {
int next_walk = node_edges[walk][0];
if (next_walk == prev_walk) {
next_walk = node_edges[walk][1];
}
return next_walk;
};
// Can we, starting from `node`, after g steps end up at node P?
auto can_from_node = [&](int node, int g) {
deque<pair<int,int>> path;
set<pair<int,int>> visited;
int prev_walk = -1;
int walk = node;
int next_walk = do_walk(walk, prev_walk); // uses default prev_walk = -1
while (g > 0) {
pair<int,int> state = make_pair(walk, next_walk);
if (visited.find(state) == visited.end()) {
visited.insert(state);
path.push_back(state);
int temp = walk;
walk = do_walk(walk, prev_walk);
prev_walk = temp;
next_walk = do_walk(walk, prev_walk);
--g;
} else {
// We've hit a cycle; trim path to just the cycle
while (path.front() != state) {
path.pop_front();
}
int c = path.size();
return path[g % c].first == P;
}
}
// After g steps, are we at P?
return path.back().first == P;
};
int g_val = G[0];
int count = 0;
for (int node = 1; node <= N; ++node) {
if (can_from_node(node, g_val)) {
count++;
}
}
answer(count);
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |