题解:P15269 「UTOI 1D」Flowerfell

· · 题解

发现形如 x x ... x 1 2 1 2 x x ... x 的构造方案很优(x 可以为任意数字),设左边有 a 个 x,右边有 b 个 x,那么 k=(a+1)(b+1) 的方案就构造完了。

但是如果 a 和 b 相差太大,就会导致方案并非最优,此时我们就需要找到更加优秀的方法。

发现 k=a^2 或 k=a(a+1) 时答案一定是最优的,由于二者本质相同,下面仅讨论 k=a^2 时的情况。

当 k=a^2 时,我们可以给出构造 3 4 3 3 3 ... 3 1 2 1 2 5 5 5 ... 5,注意第二个数是 4。

那么当 k=a^2-b\ (a>b) 时,我们只需要将上面构造的最后 b 个 5 改为 4 即可,容易证明这个构造正确且是最优的。

但是这个构造必须满足开头的数为 3 4 3,即 a\ge4,当 a<4 时可以打表或使用其他简单方法构造。

代码如下:

#include <bits/stdc++.h>
using namespace std;
int main() {
   ios::sync_with_stdio(false);
   cin.tie(nullptr);
   int d, t;
   cin >> d >> t;
   while (t--) {
      int n;
      cin >> n;
      int mn = 1e9, x = 0, y = 0;
      for (int i = 1; i <= n; i++) {
         for (int j = i; 1ll * i * j <= n; j++) {
            int k = n - i * j;
            if (i + j + k < mn) mn = i + j + k, x = i, y = j;
         }
      }
      for (int i = 1; i <= n; i++) {
         int j = (n - 1) / i + 1;
         if (i + j < mn && i >= 3 && j >= 3) mn = i + j, x = i, y = j;
      }
      if (x < y) swap(x, y);
      vector<int> ans;
      if (x * y <= n) {
         for (int i = 1; i < x; i++) ans.emplace_back(3);
         ans.emplace_back(1), ans.emplace_back(2), ans.emplace_back(1), ans.emplace_back(2);
         for (int i = 1; i < y; i++) ans.emplace_back(4);
         if (x * y ^ n) ans.emplace_back(1);
         for (int i = 1; i < n - x * y; i++) ans.emplace_back(5);
      }
      else {
         int z = x * y - n;
         ans.emplace_back(3), ans.emplace_back(4);
         for (int i = 1; i < x - 2; i++) ans.emplace_back(3);
         ans.emplace_back(1), ans.emplace_back(2), ans.emplace_back(1), ans.emplace_back(2);
         for (int i = 1; i < y - z; i++) ans.emplace_back(5);
         for (int i = 1; i <= z; i++) ans.emplace_back(4);
      }
      cout << ans.size() << "\n";
      for (auto i : ans) cout << i << " ";
      cout << "\n";
   }
   return 0;
}