fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <cmath>
  4.  
  5. using namespace std;
  6.  
  7. void solve() {
  8. int n;
  9. cin >> n;
  10.  
  11. vector<int> p(n);
  12. int curr = n - 1;
  13.  
  14. // Work backwards from the largest index
  15. while (curr >= 0) {
  16. // Find the smallest perfect square >= curr
  17. int root = ceil(sqrt(curr));
  18. int s = root * root;
  19.  
  20. // The start of the block that sums to 's'
  21. int start = s - curr;
  22.  
  23. // Fill the block in reverse
  24. for (int i = start; i <= curr; ++i) {
  25. p[i] = s - i;
  26. }
  27.  
  28. // Move to the remaining prefix
  29. curr = start - 1;
  30. }
  31.  
  32. for (int i = 0; i < n; ++i) {
  33. cout << p[i] << (i == n - 1 ? "" : " ");
  34. }
  35. cout << "\n";
  36. }
  37.  
  38. int main() {
  39. // Fast I/O
  40. ios_base::sync_with_stdio(false);
  41. cin.tie(NULL);
  42.  
  43. int t;
  44. cin >> t;
  45. while (t--) {
  46. solve();
  47. }
  48.  
  49. return 0;
  50. }
Success #stdin #stdout 0.01s 5316KB
stdin
20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
stdout
0
1 0
1 0 2
0 3 2 1
4 3 2 1 0
0 3 2 1 5 4
1 0 2 6 5 4 3
1 0 7 6 5 4 3 2
0 8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1 0
0 3 2 1 5 4 10 9 8 7 6
4 3 2 1 0 11 10 9 8 7 6 5
0 3 2 1 12 11 10 9 8 7 6 5 4
1 0 2 13 12 11 10 9 8 7 6 5 4 3
1 0 14 13 12 11 10 9 8 7 6 5 4 3 2
0 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1 0 7 6 5 4 3 2 17 16 15 14 13 12 11 10 9 8
1 0 2 6 5 4 3 18 17 16 15 14 13 12 11 10 9 8 7
0 3 2 1 5 4 19 18 17 16 15 14 13 12 11 10 9 8 7 6