1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
|
#include <bits/stdc++.h> using namespace std; #define resetIO(x) \ freopen(#x ".in", "r", stdin), freopen(#x ".out", "w", stdout) #define debug(fmt, ...) \ fprintf(stderr, "[%s:%d] " fmt "\n", __FILE__, __LINE__, ##__VA_ARGS__) template <class _Tp> inline _Tp& read(_Tp& x) { bool sign = false; char ch = getchar(); double tmp = 1; for (; !isdigit(ch); ch = getchar()) sign |= (ch == '-'); for (x = 0; isdigit(ch); ch = getchar()) x = x * 10 + (ch ^ 48); return sign ? (x = -x) : x; } template <class _Tp> inline void write(_Tp x) { if (x < 0) putchar('-'), x = -x; if (x > 9) write(x / 10); putchar((x % 10) ^ 48); } bool m_be; using ll = long long; using ld = long double; const int MAXN = 1e5 + 10; const int MAXM = 35; const int INF = 0x3f3f3f3f; int n, L, P, pre[MAXN]; char str[MAXN][MAXM]; ll sum[MAXN]; ld dp[MAXN]; struct Node { int p, l, r; } que[MAXN]; inline ld qpow(ld x, int y) { ld ret = 1; for (; y; y >>= 1, x *= x) if (y & 1) ret *= x; return ret; } inline ld calc(int p, int i) { return dp[p] + qpow(abs(sum[i] - sum[p] - 1 - L), P); } inline int bound(int l, int r, int p, int i) { int ret = r + 1; while (l <= r) { int mid = (l + r) >> 1; if (calc(p, mid) >= calc(i, mid)) r = mid - 1, ret = mid; else l = mid + 1; } return ret; } bool m_ed; signed main() { int cas; read(cas); while (cas--) { read(n), read(L), read(P); for (int i = 1; i <= n; ++i) { scanf("%s", str[i]); sum[i] = sum[i - 1] + strlen(str[i]) + 1; } int fr = 1, bk = 0; que[++bk] = {0, 1, n}; for (int i = 1; i <= n; ++i) { while (fr < bk && que[fr].r < i) ++fr; que[fr].l = i + 1; dp[i] = calc(que[fr].p, i), pre[i] = que[fr].p; while (fr < bk && calc(que[bk].p, que[bk].l) >= calc(i, que[bk].l)) --bk; int t = bound(que[bk].l, que[bk].r, que[bk].p, i); if (t <= n) que[bk].r = t - 1, que[++bk] = {i, t, n}; } if (dp[n] > 1e18) { puts("Too hard to arrange"); } else { printf("%.0Lf\n", round(dp[n])); vector<int> vec; for (int i = n; i; i = pre[i]) vec.push_back(i); reverse(vec.begin(), vec.end()); for (auto i : vec) for (int j = pre[i] + 1; j <= i; ++j) printf("%s%c", str[j], " \n"[j == i]); } puts("--------------------"); } return 0; }
|