PAT-A 1038. Recover the Smallest Number (30)

    xiaoxiao2021-03-25  68

    题目链接在此。

    STL string的常见用法。

    题意

    给出若干有前导0的数字串,将它们按某个顺序拼接。

    思路

    刚开始想,按照字典序从小到大对这些字符串排序就可以了,但是后来发现,样例就过不了。比如{321, 32}这两个字符串组合,若按照字典序组合结果是32321,但是32132才是最佳组合。所以这种策略是错误的。 正确的策略是:若有两个字符串a, b,如果a+b < b+a,则把a放在b之前。这种策略才是正确的。 最后需要注意去掉前导0。

    #include<cstdio> #include<cstring> #include<algorithm> #include<string> #include<iostream> using namespace std; bool cmp(string a, string b){ return a+b < b+a; } int main(){ int n; scanf("%d",&n); string a[n]; for(int i = 0; i < n; i++){ cin >> a[i]; } sort(a,a+n, cmp); string str; for(int i = 0; i < n; i++){ str += a[i]; } //法1: 略过前导0不输出 string::iterator it = str.begin(); for(it; *it == '0' && it != str.end(); it++){}; //略过前导0 if(it == str.end()){ cout << 0; }else{ for(it; it != str.end(); it++){ cout << *it; } } //法二:去除前导0 // while(str.size() != 0 && str[0] == '0'){ // str.erase(str.begin()); // } // if(str.size() == 0){ //结果为0 需要特判 // cout << '0' << endl; // }else{ // cout << str << endl; // } return 0; }
    转载请注明原文地址: https://ju.6miu.com/read-32337.html

    最新回复(0)