Uva 10905 — Children's Game

来源:互联网 发布:php开源问答系统 编辑:程序博客网 时间:2024/05/22 13:36

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 the N integers.

Sample Input

Output for Sample Input

4
123 124 56 90
5
123 124 56 90 9
5
9 9 9 9 9
0

9056124123
99056124123
99999

题意:给出N个数,将这N个数排列  得到一个最大的数,string类的大小比较较为好用,但是cmp函数无法正确排列类似于9,90这样的问题,故 cmp函数中return a+b〉b+a;

代码如下:

法一:

#include<stdio.h>#include<iostream>#include<string>#include<algorithm>using namespace std;bool cmp(string a,string b){    return a+b>b+a;//重点}int main(){    string s[60];    int n,i;    while(scanf("%d",&n)&&n)    {        for(i=0;i<n;i++)            cin>>s[i];        sort(s,s+n,cmp);        for(i=0;i<n;i++)            cout<<s[i];            cout<<endl;    }return 0;}
</pre><pre code_snippet_id="432183" snippet_file_name="blog_20140721_3_1033916" name="code" class="cpp">法二
#include <cstdio>#include <cstring>#include <algorithm>using namespace std;struct node{   string s;}a[60];int n;bool cmp(node p ,node q){   if(p.s.size()== q.s.size())      return p.s > q.s;   else   {      int len =max(p.s.size(),q.s.size());      int i = 0 , j = 0 , c=0;      while(p.s[i] == q.s[j] && c<=len)      {         i=(i+1)%p.s.size()//循环判断,需要注意 数据组如 886 8 类似的数据。         j=(j+1)%q.s.size();         c++;      }      return p.s[i] > q.s[j];   }}int main(){   while(scanf("%d",&n)!=EOF && n)   {      for(int i=0; i<n; i++)         cin>>a[i].s;      sort(a,a+n,cmp);      for(int i=0; i<n; i++)         cout<<a[i].s;      printf("\n");   }   return 0;}





0 0