写在前面自定义
- 实现思路
-
string str[maxn]
或vector<string> vec_str(n);
封装数字串 - 贪心算法,局部求数字串最小组合串
- 0开头数字串处理,并打印结果
- 首先,贪心算法,局部排序属核心问题
- 其次,题目较简单,耗费20分钟(前提熟练自定义字符串比较函数)
测试用例
input:
5 32 321 3214 0229 87
output:
22932132143287
ac代码
#include<vector>
#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(string a, string b)
{
return a+b<b+a;
}
int main()
{
int n;
scanf("%d", &n);
vector<string> vec_str(n);
for(int i=0; i<n; i++)
cin >> vec_str[i];
sort(vec_str.begin(), vec_str.end(), cmp);
string ans;
for(int i=0; i<n; i++)
ans += vec_str[i];
while(ans.size() != 0 && ans[0] == '0')
ans.erase(ans.begin());
if(ans.size() == 0) cout << 0;
else cout << ans;
return 0;
}
知识点小结
- C++ string
erase()
函数有2种用法,删除单个元素、删除一个区间内的所有元素。时间复杂度均为O(N).
#include<string>
#include<iostream>
using namespace std;
int main()
{
// 删除单个元素
string ss = "12345";
cout << "ss: " << ss << " " << endl;
ss.erase(ss.begin()+4);
cout << "ss.erase(ss.begin()+24: " << ss << endl;
// 删除1个区间内所有元素
cout << endl;
ss = "678910";
cout << "ss: " << ss << " " << endl;
ss.erase(ss.begin()+2, ss.end()-1);
cout << "ss.erase(ss.begin()+2, ss.end()-1): " << ss << endl;
// 从起始位置,删除x个字符
cout << endl;
ss = "678910";
cout << "ss: " << ss << " " << endl;
ss.erase(3,3);
cout << "ss.erase(3,3): " << ss;
return 0;
}
- 打印结果
ss: 12345
ss.erase(ss.begin()+24: 1234
ss: 678910
ss.erase(ss.begin()+2, ss.end()-1): 670
ss: 678910
ss.erase(3,3): 678
Process returned 0 (0x0) execution time : 0.018 s
Press any key to continue.