- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 77 lines of C++ from the credited upstream file 3549.cpp.
- The implementation visibly relies on sequence storage.
- 10 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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 vector<long long> multiply(vector<int>& poly1, vector<int>& poly2) {4 const unsigned n1 = poly1.size();5 const unsigned n2 = poly2.size();6 const unsigned n = n1 + n2 - 1;7 const unsigned sz = 1 << std::bit_width(n - 1);8 9 10 vector<complex<double>> a(sz);11 vector<complex<double>> b(sz);12 13 14 for (int i = 0; i < n1; ++i)15 a[i] = poly1[i];16 17 for (int i = 0; i < n2; ++i)18 b[i] = poly2[i];19 20 21 fft(a, false);22 fft(b, false);23 24 25 for (int i = 0; i < sz; ++i)26 a[i] *= b[i];27 28 29 fft(a, true);30 31 32 vector<long long> ans(n);33 34 for (int i = 0; i < n; ++i)35 ans[i] = round(a[i].real());36 37 return ans;38 }39 40 private:41 42 void fft(vector<complex<double>>& a, bool inverse) {43 const unsigned n = a.size();44 45 46 for (int i = 1, j = 0; i < n; ++i) {47 int bit = n >> 1;48 for (; j & bit; bit >>= 1)49 j ^= bit;50 j ^= bit;51 if (i < j)52 swap(a[i], a[j]);53 }54 55 56 for (int len = 2; len <= n; len *= 2) {57 const double angle = 2 * M_PI / len * (inverse ? -1 : 1);58 const complex<double> w_len(cos(angle), sin(angle));59 for (int i = 0; i < n; i += len) {60 complex<double> w(1);61 for (int j = 0; j < len / 2; ++j) {62 const complex<double> u = a[i + j];63 const complex<double> v = a[i + j + len / 2] * w;64 a[i + j] = u + v;65 a[i + j + len / 2] = u - v;66 w *= w_len;67 }68 }69 }70 71 72 if (inverse)73 for (complex<double>& x : a)74 x /= n;75 }76};77