1038 Recover the Smallest Number (30 分,附详细注释,逻辑分析)

写在前面自定义
  • 实现思路
    • 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.
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xsimah

创作不易,感谢客官的打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值