博客
关于我
【笨方法学PAT】1038 Recover the Smallest Number (30 分)
阅读量:133 次
发布时间:2019-02-26

本文共 1148 字,大约阅读时间需要 3 分钟。

为了解决这个问题,我们需要将给定的数字段重新排列,使得组合起来的数最小。我们可以使用贪心算法来实现这一点。

方法思路

  • 问题分析:我们需要将给定的数字段重新排列,使得组合后的数最小。每个数字段可能包含前导零,因此在排列时需要特别注意。
  • 贪心算法:对于两个数字段a和b,我们需要决定a放在b前面还是后面,使得组合后的结果最小。我们可以比较a+b和b+a的大小,选择较小的顺序。
  • 排序:将所有数字段按照上述比较方式排序。
  • 连接和去除前导零:连接排序后的数字段,去掉前导零,得到最终结果。
  • 解决代码

    #include 
    #include
    #include
    #include
    using namespace std;bool cmp(string s1, string s2) { return s1 + s2 < s2 + s1;}int main() { int n; cin >> n; vector
    v(n); for (int i = 0; i < n; ++i) { cin >> v[i]; } sort(v.begin(), v.end(), cmp); string s; for (int i = 0; i < n; ++i) { s += v[i]; } // 去掉前导零 int start = 0; while (start < s.length() && s[start] == '0') { ++start; } if (start == s.length()) { cout << 0 << endl; } else { for (; start < s.length(); ++start) { cout << s[start]; } cout << endl; } system("pause"); return 0;}

    代码解释

  • 读取输入:首先读取输入的数字段数量n,然后读取每个数字段。
  • 排序:使用自定义的比较函数对数字段进行排序,确保每次比较都能得到最小的组合。
  • 连接数字段:将排序后的数字段连接成一个字符串。
  • 去除前导零:去掉连接后的字符串前面的零,确保输出的结果没有前导零。如果所有字符都是零,输出0。
  • 这种方法确保了我们每一步都选择了最优的排列,从而得到最小的数。

    转载地址:http://wlaf.baihongyu.com/

    你可能感兴趣的文章
    sqlserver学习笔记(三)—— 为数据库添加新的用户
    查看>>
    org.apache.http.conn.HttpHostConnectException: Connection to refused
    查看>>
    org.apache.ibatis.binding.BindingException: Invalid bound statement错误一例
    查看>>
    org.apache.ibatis.exceptions.PersistenceException:
    查看>>
    org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
    查看>>
    org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
    查看>>
    org.apache.poi.hssf.util.Region
    查看>>
    org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
    查看>>
    org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
    查看>>
    org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:processDebugManifest'
    查看>>
    org.hibernate.HibernateException: Unable to get the default Bean Validation factory
    查看>>
    org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
    查看>>
    org.springframework.amqp.AmqpConnectException:java.net.ConnectException:Connection timed out:connect
    查看>>
    org.springframework.beans.factory.BeanDefinitionStoreException
    查看>>
    org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata
    查看>>
    org.springframework.boot:spring boot maven plugin丢失---SpringCloud Alibaba_若依微服务框架改造_--工作笔记012
    查看>>
    SQL-CLR 类型映射 (LINQ to SQL)
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>
    org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
    查看>>