|
| 1 | +/* |
| 2 | + |
| 3 | +time: O() |
| 4 | +space: O() |
| 5 | +
|
| 6 | +Runtime: 218 ms, faster than 93.81% of C++ online submissions for Shortest Impossible Sequence of Rolls. |
| 7 | +Memory Usage: 113.7 MB, less than 54.58% of C++ online submissions for Shortest Impossible Sequence of Rolls. |
| 8 | +*/ |
| 9 | + |
| 10 | +#include <bits/stdc++.h> |
| 11 | + |
| 12 | +using namespace std; |
| 13 | + |
| 14 | +#define all(x) begin(x), end(x) |
| 15 | +typedef vector<int> vi; |
| 16 | +typedef vector<vector<int>> vvi; |
| 17 | + |
| 18 | +class Solution { |
| 19 | +public: |
| 20 | + int shortestSequence(vector<int>& rolls, int k) { |
| 21 | + /// position sequence of any given number |
| 22 | + vector<vi> pos_seqs(k+1); |
| 23 | + int pos = 0; |
| 24 | + for (auto & roll : rolls){ |
| 25 | + pos_seqs[roll].push_back(pos++); |
| 26 | + } |
| 27 | + |
| 28 | + /// position of any given number now |
| 29 | + vector<vi::iterator> pos_now_its(k+1); |
| 30 | + int res = 1; |
| 31 | + int pos_next_min = 0; |
| 32 | + for (int i=1; i<=k; ++i){ |
| 33 | + if (pos_seqs[i].size() == 0){ |
| 34 | + return res; |
| 35 | + } |
| 36 | + pos_now_its[i] = pos_seqs[i].begin(); |
| 37 | + pos_next_min = max(pos_next_min, pos_seqs[i][0]+1); |
| 38 | + } |
| 39 | + |
| 40 | + int pos_now_min; |
| 41 | + vi::iterator it; |
| 42 | + for (res = 2;; ++res){ |
| 43 | + pos_now_min = pos_next_min; |
| 44 | + for (int i=1; i<=k; ++i){ |
| 45 | + it = lower_bound(pos_now_its[i], pos_seqs[i].end(), pos_now_min); |
| 46 | + if (it == pos_seqs[i].end()){ |
| 47 | + return res; |
| 48 | + } else { |
| 49 | + pos_now_its[i] = it; |
| 50 | + pos_next_min = max(pos_next_min, *it+1); |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | +}; |
| 56 | + |
| 57 | +const static auto initialize = [] { |
| 58 | + std::ios::sync_with_stdio(false); |
| 59 | + std::cin.tie(nullptr); |
| 60 | + std::cout.tie(nullptr); |
| 61 | + return nullptr; |
| 62 | +}(); |
0 commit comments