System Testing
23 / 23
AC
23/23 test cases passed
Submission #21
| Problem | RandomizedParking |
|---|---|
| Handle | you |
| Submitted | 2026-07-19 07:27:56 |
Source Code
#include <vector>
#include <string>
using namespace std;
class RandomizedParking {
public:
double solve(string start, int K) {
int N = start.length();
int start_mask = 0;
// Build the initial state mask
for (int i = 0; i < N; ++i) {
if (start[i] == 'X') {
start_mask |= (1 << i);
}
}
// DP table tracking probability of each state
vector<double> dp(1 << N, 0.0);
vector<int> current_states;
dp[start_mask] = 1.0;
current_states.push_back(start_mask);
// Process each car arriving one by one
for (int step = 1; step <= K; ++step) {
vector<double> next_dp;
vector<int> next_states;
if (step < K) {
next_dp.assign(1 << N, 0.0);
}
double expected = 0.0;
// Compute outcomes from all possible current states
for (int S : current_states) {
double prob = dp[S];
if (prob == 0.0) continue;
int empty_spots[20];
int num_empty = 0;
// Identify all currently empty spots
for (int i = 0; i < N; ++i) {
if (!(S & (1 << i))) {
empty_spots[num_empty++] = i;
}
}
// Calculate the effect of each block of entrances ending at an empty spot
for (int k = 0; k < num_empty; ++k) {
int curr = empty_spots[k];
int prev = (k == 0) ? empty_spots[num_empty - 1] : empty_spots[k - 1];
int d = (curr - prev + N) % N;
if (d == 0) d = N; // Case where only 1 empty spot is left
if (step == K) {
// K-th car: Calculate expected occupied spots encountered
expected += prob * ((double)d * (d - 1) / 2.0) / N;
} else {
// Preceding car: Transition probabilities to the new state
int next_S = S | (1 << curr);
if (next_dp[next_S] == 0.0) {
next_states.push_back(next_S);
}
next_dp[next_S] += prob * (double)d / N;
}
}
}
// If we've processed the target K-th car, we're done
if (step == K) {
return expected;
} else {
dp = std::move(next_dp);
current_states = std::move(next_states);
}
}
return 0.0;
}
};