题解:AT_abc471_f [ABC471F] Concat (maximize)

· · 题解

贪心好题,欢迎来 hack。

题意简述

给你一个由数字组成的 N 字符串 S_1,\ldots,S_N 。

从这些字符串中选 K 个字符串任意顺序排列后拼接,求所有可能拼成的字符串在解释为十进制整数(去掉多余的前导零后)后的最大可能值。

空字符串十进制整数值为 0。

## 做法 首先有如下显然做法: * 枚举第一个选哪一个; * 剩下的先按照长度排序,长度相同再按照字典序排序; * 必然选前 $k - 1$ 个; * 然后用[拼数](https://www.luogu.com.cn/problem/P1012)的做法排序这 $k$ 个字符串,得到 $ans_i$; * $Ans = \min {ans_i}$。 但是这个不好处理,不精细处理会 TLE,考虑更简单的做法。 --- 注意到“先按照长度排序,长度相同再按照字典序排序”后,按照前面的做法分讨得:前 $k-1$ 个必然会选。 考虑还有一个放到这 $k$ 个字符串形成的序列的位置。 1. 放开头,则去掉前导 $0$ 后,数值越大越好。去掉前导 $0$,先按照长度排序,长度相同再按照字典序排序,选第一大; 2. 放中间或者末尾,此时前导 $0$ 必然被使用,则按照原来排序后的第 $k+1$ 到 $n$ 必然没有第 $k$ 优秀,所以一定选择第 $k$ 个。 综上,我们做完了这题。 ```cpp #include <bits/stdc++.h> using namespace std; const int N = 1e5 + 5; int n,k; string a[N]; int main() { cin >> n >> k; for(int i = 1; i <= n; i++) cin >> a[i]; sort(a + 1,a + n + 1,[](string &x,string &y) { return x.size() == y.size()? x > y : x.size() > y.size(); }); vector<string> a2; for(int i = k; i <= n; i++) { int p = 0; while(p < a[i].size() && a[i][p] == '0') p++; a2.push_back(a[i].substr(p)); } string ans1 = "",ans2 = "",ans = ""; sort(a + 1,a + k,[](string &x,string &y) { return x + y > y + x; }); for(int i = 1; i < k; i++) ans1 += a[i]; sort(a2.begin(),a2.end(),[](string &x,string &y) { return x.size() == y.size()? x > y : x.size() > y.size(); }); ans1 = a2.front() + ans1; sort(a + 1,a + k + 1,[](string &x,string &y) { return x + y > y + x; }); for(int i = 1; i <= k; i++) ans2 += a[i]; int p1 = 0; while(p1 < ans1.size() && ans1[p1] == '0') p1++; ans1 = ans1.substr(p1); int p2 = 0; while(p2 < ans2.size() && ans2[p2] == '0') p2++; ans2 = ans2.substr(p2); if(ans1.size() > ans2.size() || ans1.size() == ans2.size() && ans1 > ans2) ans = ans1; else ans = ans2; if(ans.size()) cout << ans << "\n"; else cout << "0\n"; return 0; } ```