1. 程式人生 > >UVA10905 Children's Game【排序】

UVA10905 Children's Game【排序】

There are lots of number games for children. These games are pretty easy to play but not so easy tomake. 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 are4 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 surethat 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 justgot the idea of number?

Input

Each input starts with a positive integer N (≤ 50). In next lines there are N positive integers. Inputis 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 allthe N integers.

Sample Input

4

123 124 56 90

5

123 124 56 90 9

5

9 9 9 9 90

Sample Output

9056124123

99056124123

99999

題意簡述

  輸入n個正整數,將其連成一個最大的整數。

問題分析:(略)

程式說明

  本題有三大要點,一是並非把大的整數放在前面,例如12和3,構成的最大整數是312;二是也不能夠簡單地用函式strcmp()進行比較,例如9和90,構成的最大整數為990而不是909;三是n個整數裡,有的可能是大整數,編寫了一個C語言的程式,總是AC不了,後來終於明白了。

AC的C++語言程式如下:

/* UVA10905 Children's Game */

#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;

const int MAXN = 50;
string val[MAXN];

bool cmp(string a ,string b)
{
   return a+b > b+a;
}

int main()
{
    int n;

    while(scanf("%d",&n)!=EOF && n != 0)  {
      for(int i=0; i<n; i++)
         cin >> val[i];

      sort(val, val + n, cmp);

      for(int i=0; i<n; i++)
         cout << val[i];
      cout << endl;
   }

   return 0;
}

沒有AC的C語言程式如下:
/* UVA10905 Children's Game */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef unsigned long long ULL;

#define MAXN 50

int n;
ULL val[MAXN];

char sa[20], sb[20], sab[40], sba[40];

int cmp(const void * a, const void * b)
{
    sprintf(sa, "%llu", *(ULL *)a);
    sprintf(sab, "%llu", *(ULL *)a);

    sprintf(sb, "%llu", *(ULL *)b);
    sprintf(sba, "%llu", *(ULL *)b);

    strcat(sab, sb);
    strcat(sba, sa);

    return strcmp(sba, sab);
}

int main(void)
{
    int i;

    while(scanf("%d", &n) != EOF && n != 0) {
        for(i=0; i<n; i++)
            scanf("%llu", &val[i]);

        qsort(val, n, sizeof(val[0]), cmp);

        for(i=0; i<n; i++)
            printf("%llu", val[i]);
        printf("\n");
    }

    return 0;
}