UVA10905 Children's Game

问题链接:UVA10905 Children's Game基础级练习题,用C++语言编写程序。

题意简述:输入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("
");
    }

    return 0;
}


原文地址:https://www.cnblogs.com/tigerisland/p/7564461.html