DP with Simulation, easy to understand
Intuition\nWe can just simulate the whole process, and then leverage DP to speed it up\n\n# Approach\nlet fv[i] be the time that [i] is visited for the first,\n
# Intuition\nWe can just simulate the whole process, and then leverage DP to speed it up\n\n# Approach\nlet `fv[i]` be the time that `[i]` is visited for the first,\nthen the second time that we\'ll visit `[i]` again (after jumping back to\n`nextVisit[i]`) is:\n`t += 1 + fv[cur] - fv[nextVisit[cur]]`\n\n# Complexity\n- Time complexity:\nO(n), because `cur` never retrogresses and the loop takes ~2n iterations.\n\n- Space complexity:\nO(n)\n\n# Code\n```cpp []\n// Idea: DP with memo to avoid repeated computation, and simulation.\n// let fv[i] be the time that [i] is visited for the first,\n// then the second time that we\'ll visit [i] again (after jumping back to\n// nextVisit[i]) is:\n//  t += 1 + fv[cur] - fv[nextVisit[cur]]\n//\nclass Solution {\npublic:\n    int firstDayBeenInAllRooms(vector<int>& nextVisit) {\n        const int Mod = 1\'000\'000\'007;\n        const int n = nextVisit.size();\n        // first visits: fv[i] is the time that [i] is visited for the first\n        // time\n        vector<long long> fv(n, -1);\n        vector<bool> vis(n);\n        fv[0] = 0;\n        // simulation with the jumps via fv\n        int cur = 0;\n        long long t = 0;\n        while (cur < n - 1) {\n            if (vis[cur]) { // for the second time\n                vis[cur] = false;\n                cur++;\n                t = (t + 1) % Mod;\n            } else { // for the first time\n                fv[cur] = t;\n                vis[cur] = true;\n                // we\'ll jump back to nextVisit[cur] (taking 1 unit of time),\n                // and then take `fv[cur] - fv[nextVisit[cur]]` units of time to\n                // reach cur again:\n                t = (t + 1 + Mod + fv[cur] - fv[nextVisit[cur]]) % Mod;\n            }\n        }\n        return t;\n    }\n};\n```
['C++']