1. Recursive Exploration of All Line Choices
Intuition
At every station, branch into either staying on the current line or switching to the opposite line. Base case reaches station n and adds exit times.
Algorithm
- Define
findMin(station, currentLine). - If station == n - 1, return
a[currentLine][station] + x[currentLine]. - Option 1: stay on currentLine -> cost is
a[currentLine][station] + findMin(station + 1, currentLine). - Option 2: switch to
1 - currentLine-> cost isa[currentLine][station] + t[currentLine][station] + findMin(station + 1, 1 - currentLine). - Return min(Option 1, Option 2).
#include <iostream>#include <vector>#include <algorithm> using namespace std; int solveRec(int j, int line, int n, const vector<vector<int>>& a, const vector<vector<int>>& t, const vector<int>& x) { if (j == n - 1) { return a[line][j] + x[line]; } int stay = a[line][j] + solveRec(j + 1, line, n, a, t, x); int transfer = a[line][j] + t[line][j] + solveRec(j + 1, 1 - line, n, a, t, x); return min(stay, transfer);} int carAssemblyRecursive(int n, const vector<vector<int>>& a, const vector<vector<int>>& t, const vector<int>& e, const vector<int>& x) { int startLine1 = e[0] + solveRec(0, 0, n, a, t, x); int startLine2 = e[1] + solveRec(0, 1, n, a, t, x); return min(startLine1, startLine2);} int main() { vector<vector<int>> a = {{4, 5, 3, 2}, {2, 10, 1, 4}}; vector<vector<int>> t = {{7, 4, 5}, {9, 2, 8}}; vector<int> e = {10, 12}; vector<int> x = {18, 7}; cout << "Min Time (Recursive): " << carAssemblyRecursive(4, a, t, e, x) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^n) - Space complexity:
O(n) recursion call stack