4th IIUC Inter-University Programming Contest, 2005 |
|
A |
Children’s Game |
Input: standard input |
|
Problemsetter: Md. Kamruzzaman |
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 |
9056124123 |
题目大意:给定N个数字,把N个数字连接起来,使得新产生的数字的值最大。
题解:这题看似很简单,好像只需用strcmp对数字字符串进行比较并排序,但是会WA,这里有一个陷阱,这组数据28 282,如果直接strcmp(28,282),那么产生的新数字将是28228,但实际可以产生的最大数字是28282。所以这种方法是不行的,我们需要换一种方法。这种方法很简单,对于数字串s1,s2,比较s1s2和s2s1,如果s1s2<s2s1,那么把两个数字字符串进行交换,数据量不大,用选择排序即可。
1 #include<stdio.h> 2 #include<string.h> 3 #define MAXN 55 4 int main(void) 5 { 6 char s[MAXN][1000],s1[1000],s2[1000],temp[1000]; 7 int i,j,n; 8 while(scanf("%d",&n)!=EOF) 9 { 10 if(!n) break; 11 for(i=0;i<n;i++) 12 { 13 getchar(); 14 scanf("%s",s[i]); 15 } 16 for(i=0;i<n-1;i++) 17 for(j=i+1;j<n;j++) 18 { 19 strcpy(s1,s[i]); 20 strcat(s1,s[j]); 21 strcpy(s2,s[j]); 22 strcat(s2,s[i]); 23 if(strcmp(s1,s2)<0) 24 { 25 strcpy(temp,s[i]); 26 strcpy(s[i],s[j]); 27 strcpy(s[j],temp); 28 29 } 30 } 31 for(i=0;i<n;i++) 32 printf("%s",s[i]); 33 printf("\n"); 34 35 } 36 return 0; 37 }