Approach
Depth-first search
For Minimum Runes to Add to Cast Spell, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 77 lines of C++ from the credited upstream file 3383.cpp.
- The implementation visibly relies on sequence storage.
- 8 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int minRunesToAdd(int n, vector<int>& crystals, vector<int>& flowFrom,4 vector<int>& flowTo) {5 vector<vector<int>> graph(n);6 vector<vector<int>> reversedGraph(n);7 8 for (int i = 0; i < flowFrom.size(); ++i) {9 const int u = flowFrom[i];10 const int v = flowTo[i];11 graph[u].push_back(v);12 reversedGraph[v].push_back(u);13 }14 15 16 vector<bool> seen(n);17 vector<int> orderStack;18 vector<int> componentIds(n, -1);19 int componentCount = 0;20 21 for (int i = 0; i < n; ++i)22 if (!seen[i])23 kosaraju(graph, i, seen, orderStack);24 25 for (int i = n - 1; i >= 0; --i) {26 const int u = orderStack[i];27 if (componentIds[u] == -1)28 identifySCC(reversedGraph, u, componentIds, componentCount++);29 }30 31 32 vector<bool> hasCrystal(componentCount);33 vector<bool> hasInterComponentEdge(componentCount);34 35 for (const int u : crystals)36 hasCrystal[componentIds[u]] = true;37 38 for (int i = 0; i < flowFrom.size(); ++i) {39 const int id1 = componentIds[flowFrom[i]];40 const int id2 = componentIds[flowTo[i]];41 if (id1 != id2) 42 hasInterComponentEdge[id2] = true;43 }44 45 46 int ans = 0;47 48 for (int i = 0; i < componentCount; ++i)49 if (!hasCrystal[i] && !hasInterComponentEdge[i])50 ++ans;51 52 return ans;53 }54 55 private:56 57 void kosaraju(const vector<vector<int>>& graph, int u, vector<bool>& seen,58 vector<int>& orderStack) {59 seen[u] = true;60 for (const int v : graph[u])61 if (!seen[v])62 kosaraju(graph, v, seen, orderStack);63 orderStack.push_back(u);64 }65 66 67 void identifySCC(const vector<vector<int>>& reversedGraph, int u,68 vector<int>& componentIds, int componentId) {69 if (componentIds[u] != -1)70 return;71 componentIds[u] = componentId;72 for (const int v : reversedGraph[u])73 if (componentIds[v] < 0)74 identifySCC(reversedGraph, v, componentIds, componentId);75 }76};77