题目链接:
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=113&page=show_problem&problem=1846
类型: 排序
There are lots of number games for children. These games are pretty easy to play but not so easy to make. We will discuss about an interesting game here. Each player will be given N positive integer. (S)He can make a big integer by appending those integers after one another. Such as if there are 4 integers as 123, 124, 56, 90 then the following integers can be made – 1231245690, 1241235690, 5612312490, 9012312456, 9056124123 etc. In fact 24 such integers can be made. But one thing is sure that 9056124123 is the largest possible integer which can be made.
You may think that it’s very easy to find out the answer but will it be easy for a child who has just got the idea of number?
Input
Each input starts with a positive integer N (≤ 50). In next lines there are N positive integers. Input is terminated by N = 0, which should not be processed.
Output
For each input set, you have to print the largest possible integer which can be made by appending all theN integers.
题目大意:
输入一串数字, 要求输出有这些数字能拼成的最大的数字
分析与总结:
要让一个数字最大的话,就要让它的高位尽量的大。所以容易可以想到直接对这些数字按字典序(把他们看成字符串)从大到小进行排序,然后直接输出了。
我真的这么做了, 然后,就WA了。
原因在于, 例如这三个数: 12, 1211, 11, 直接排序后是1219, 12,11, 得到12191211, 但是正确的排序应该是12,1219,11, 为12121911。
进行排序时,如果位数相等的话,那么直接可以字典序比较。 不相等的话,例如1219和12, 那么就不能这样了。那怎样判断呢?很明显,这两个数要么第一个在前要么就是第二个在前, 直接比较这两种情况那个更大即可。
/* * UVa 10905 - Children's Game * Time : 0.176s (UVa) * Author: D_Double */ #include<iostream> #include<cstdio> #include<string> #include<algorithm> using namespace std; typedef string BigNum; BigNum arr[52]; bool cmp (const string & a, const string & b){ if(a.size()==b.size()) return a > b; string tmp1 = a+b , tmp2 = b+a; return tmp1 > tmp2; } int main(){ freopen("input.txt","r",stdin); int n, i; while(scanf("%d",&n), n){ for(i=0; i<n; ++i) cin >> arr[i]; sort(arr, arr+n, cmp); for(i=0; i<n; ++i) cout << arr[i]; printf("\n"); } return 0; }
—— 生命的意义,在于赋予它意义。
原创 http://blog.csdn.net/shuangde800 , By D_Double (转载请标明)