【九度】题目1392:排序生成最小的数

108 篇文章 0 订阅
102 篇文章 5 订阅

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

还记得陈博是个数字完美主义者么?^_^....这次,他又闹脾气了!我们知道计算机中常常要使用数组保存一组数字,但是今天他就要求把数组里的所有数字组成一个,并且这个数字是这些数字所能组成的所有数字中最小的一个,否则他会抓狂的!!!例如:数组{3,32,321},可以组成6个数字3|32|321, 3|321|32, 32|3|321, 32|321|3, 321|32|3, 321|3|32, 最小的就是321323 (321|32|3).
输入:
输入有多组数据,每组数据包括2行。
第一行包括一个整数n(1<=n<=100),表示数组的大小。接下来一行有n个正整数,每个数都满足[ 1,   1000,000,000 ]。
输出:
对应每组数据,输出这个数组所能组成的最小的那个数。
样例输入:
3
32 3 321
5
5 4 3 2 1

样例输出:
321323
12345

排序题的变型题。
万变不离其宗。
这次排序选择二者组合较小。

C++ AC

#include <iostream>
#include <algorithm>
#include <string>
const int maxn = 102;
using namespace std;
int n,i;
string array[maxn];
 
bool cmp(string s1, string s2){ 
    return (s1 + s2) < ( s2 + s1) ;
}
 
int main(){
 
    while(cin >> n){
        for(i = 0; i < n; i++ ){
            cin >> array[i];
        }        
        sort(array,array + n,cmp);
        string result="";
        for(i = 0; i < n; i++ ){
            result += array[i];
        }
        cout<<result<<endl;
    }
    return 0;
}
/**************************************************************
    Problem: 1392
    User: wangzhenqing
    Language: C++
    Result: Accepted
    Time:180 ms
    Memory:1528 kb
****************************************************************/

Java AC

import java.io.StreamTokenizer;
import java.util.Arrays;
import java.util.Comparator;
 
public class Main{
    /*
     * 1392
     */
    public static void main(String[] args) throws Exception {
        StreamTokenizer st = new StreamTokenizer(System.in);
        while (st.nextToken() != StreamTokenizer.TT_EOF) {
            int n = (int) st.nval;
            Integer array[] = new Integer[n];
            for (int i = 0; i < n; i++) {
                st.nextToken();
                array[i] = (int) st.nval;
            }
            Arrays.sort(array , new MySort());
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < n; i++) {
                sb.append(array[i]);
            }
            System.out.println(sb.toString());
        }
    }
    static class MySort implements Comparator<Integer>{
 
        public int compare(Integer o1, Integer o2) {
            String ab = o1+""+o2;
            String ba = o2+""+o1;
            int res = ab.compareTo(ba);
            return res;
        }
    }
}
 
/**************************************************************
    Problem: 1392
    User: wzqwsrf
    Language: Java
    Result: Accepted
    Time:1900 ms
    Memory:128020 kb
****************************************************************/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值