Python实现Pat 1032. Sharing (25)

谁践踏了优雅 2022-06-04 06:49 305阅读 0赞

题目

Given a collection of number segments, you are supposed to recover the smallest number from them. For example, given {32, 321, 3214, 0229, 87}, we can recover many numbers such like 32-321-3214-0229-87 or 0229-32-87-321-3214 with respect to different orders of combinations of these segments, and the smallest number is 0229-321-3214-32-87.

Input Specification:

Each input file contains one test case. Each case gives a positive integer N (<=10000) followed by N number segments. Each segment contains a non-negative integer of no more than 8 digits. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the smallest number in one line. Do not output leading zeros.

Sample Input:
5 32 321 3214 0229 87
Sample Output:
22932132143287

解答

排序题,关键在于字符串的大小比较。比较两个字符串大小时如32和321,如果有相同前缀,则删除较长的字符串中的前缀,并比较剩下的数的大小,即32和321的比较结果应该是32和1的比较结果。

  1. from functools import cmp_to_key
  2. def cmpt(s1,s2):
  3. len1=len(s1)
  4. len2=len(s2)
  5. maxl=max(len1,len2)
  6. for i in range(maxl):
  7. if s1[i%len1]!=s2[i%len2]:
  8. return int(s1[i%len1])-int(s2[i%len2])
  9. else:
  10. return 0
  11. line0=input().split(' ')[1:]
  12. line0.sort(key=cmp_to_key(cmpt))
  13. num=''
  14. for e in line0:
  15. num+=e
  16. count=0
  17. #剔除无效的‘0’
  18. for e in num:
  19. if e=='0':
  20. count+=1
  21. else:
  22. break
  23. num=num[count:]
  24. #特殊情况
  25. if not num:
  26. num='0'
  27. print (num)

又错了一个小点。不管了
这里写图片描述

发表评论

表情:
评论列表 (有 0 条评论,305人围观)

还没有评论,来说两句吧...

相关阅读

    相关 PAT乙级1032

    1032 挖掘机技术哪家强 (20 分) 为了用事实说明挖掘机技术到底哪家强,PAT 组织了一场挖掘机技能大赛。现请你根据比赛结果统计出技术最强的那个学校。 输入格式: