|
| 1 | +#include<bits/stdc++.h> |
| 2 | + |
| 3 | +using namespace std; |
| 4 | + |
| 5 | +typedef long long int LL; |
| 6 | +typedef vector<LL> VLL; |
| 7 | +typedef std::complex<double> CD; |
| 8 | + |
| 9 | +#define PB push_back |
| 10 | +#define F first |
| 11 | +#define s second |
| 12 | +#define SZ(x) x.size() |
| 13 | +#define ALL(a) std::begin(a), std::end(a) |
| 14 | +#define IN_REP int _t; cin >> _t ; while(_t--) |
| 15 | +#define IOS ios::sync_with_stdio(false);cin.tie(NULL) |
| 16 | +#define FOR(i, a, b) for(int i=(a);i<(b);i++) |
| 17 | +#define REP(i, n) FOR(i,0,n) |
| 18 | +const double PI = acos(-1); |
| 19 | +typedef std::valarray<CD> CArray; |
| 20 | + |
| 21 | +// Cooley–Tukey FFT (in-place) |
| 22 | +void fft(CArray &x) { |
| 23 | + // const size_t N = x.size(); |
| 24 | + int N = SZ(x); |
| 25 | + if (N <= 1) return; |
| 26 | + |
| 27 | + // divide |
| 28 | + CArray even = x[std::slice(0, N / 2, 2)]; |
| 29 | + CArray odd = x[std::slice(1, N / 2, 2)]; |
| 30 | + |
| 31 | + // conquer |
| 32 | + fft(even); |
| 33 | + fft(odd); |
| 34 | + |
| 35 | + // combine |
| 36 | + // for (size_t k = 0; k < N/2; ++k){ |
| 37 | + for (int k = 0; k < N / 2; ++k) { |
| 38 | + CD t = std::polar(1.0, -2 * PI * k / N) * odd[k]; |
| 39 | + x[k] = even[k] + t; |
| 40 | + x[k + N / 2] = even[k] - t; |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +// inverse fft (in-place) |
| 45 | +void ifft(CArray &x) { |
| 46 | + // conjugate the complex numbers |
| 47 | + x = x.apply(std::conj); |
| 48 | + |
| 49 | + // forward fft |
| 50 | + fft(x); |
| 51 | + |
| 52 | + // conjugate the complex numbers again |
| 53 | + x = x.apply(std::conj); |
| 54 | + |
| 55 | + // scale the numbers |
| 56 | + x /= x.size(); |
| 57 | +} |
| 58 | + |
| 59 | +int main() { |
| 60 | + IOS; |
| 61 | + IN_REP { |
| 62 | + int n; |
| 63 | + cin >> n; |
| 64 | + n++; // Given in question |
| 65 | + int size = 2 * (1 << int(ceil(log2(n)))); |
| 66 | + |
| 67 | + CArray x(size), y(size); |
| 68 | + FOR(i, size - n, size) cin >> x[i]; |
| 69 | + fft(x); |
| 70 | + FOR(i, size - n, size) cin >> y[i]; |
| 71 | + fft(y); |
| 72 | + |
| 73 | + CArray res(size); |
| 74 | + res = x * y; |
| 75 | + ifft(res); |
| 76 | + VLL ans; |
| 77 | + REP(i, size - 1) { |
| 78 | + ans.PB(round(res[i].real())); |
| 79 | + } |
| 80 | + for (int i = size - 1 - (2 * n - 1); i < size - 1; i++) { |
| 81 | + cout << ans[i] << " "; |
| 82 | + } |
| 83 | + cout << endl; |
| 84 | + } |
| 85 | + return 0; |
| 86 | +} |
0 commit comments