九度OJ 1504 把数组排成最小的数【算法】-- 2009年百度面试题

题目地址:http://ac.jobdu.com/problem.php?pid=1504

题目描述:

输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。

输入:

输入可能包含多个测试样例。
对于每个测试案例,输入的第一行为一个整数m (1<=m <=100)代表输入的正整数的个数。
输入的第二行包括m个正整数,其中每个正整数不超过10000000。

输出:

对应每个测试案例,
输出m个数字能排成的最小数字。

样例输入:
3
23 13 6
2
23456 56
样例输出:
13236
2345656
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
 
int compare (const void * p, const void * q){
    char str1[20];
    char str2[20];
     
    strcpy (str1, (const char *)p);
    strcat (str1, (const char *)q);
 
    strcpy (str2, (const char *)q);
    strcat (str2, (const char *)p);
 
    return strcmp (str1, str2);
}
 
int main (void){
    char str[100][10];
    int m;
    int i;
 
    while (scanf ("%d", &m) != EOF){
        for (i=0; i<m; ++i){
            scanf ("%s", &str[i]);
        }
        qsort (str, m, sizeof(char) * 10, compare);
        for (i=0; i<m; ++i){
            printf ("%s", str[i]);
        }
        putchar ('
');
    }
 
    return 0;
}

参考资料:何海涛 -- 程序员面试题精选100题(41)-把数组排成最小的数[算法]

原文地址:https://www.cnblogs.com/liushaobo/p/4373800.html