1. 程式人生 > >牛客網------數串題

牛客網------數串題

題目描述

設有n個正整數,將他們連線成一排,組成一個最大的多位整數。 如:n=3時,3個整數13,312,343,連成的最大整數為34331213。 如:n=4時,4個整數7,13,4,246連線成的最大整數為7424613。

輸入描述:

有多組測試樣例,每組測試樣例包含兩行,第一行為一個整數N(N<=100),第二行包含N個數(每個數不超過1000,空格分開)。

輸出描述:

每組資料輸出一個表示最大的整數。

示例1

輸入

2 12 123 4 7 13 4 246

輸出

12312 7424613

我用的C++,解答是:

#include<iostream> #include<vector> #include<algorithm> #include<string> using namespace std; bool big_to_small(string s1,string s2) {     return (s1+s2)>(s2+s1); } int main() {     int num;     vector<string> input;     string in;     while(cin>>num)     {         for(int i=0;i<num;i++)         {             cin>>in;             input.push_back(in);         }     }     sort(input.begin(),input.end(),big_to_small);     for(vector<string>::iterator it=input.begin();it!=input.end();it++)         cout<<*it; }

若有好的方法歡迎交流!

備註:

C++ sort排序函式用法

sort類函式:

函式名 功能描述
sort 對給定區間所有元素進行排序
stable_sort 對給定區間所有元素進行穩定排序
partial_sort 對給定區間所有元素部分排序
partial_sort_copy 對給定區間複製並排序
nth_element 找出給定區間的某個位置對應的元素
is_sorted 判斷一個區間是否已經排好序
partition 使得符合某個條件的元素放在前面
stable_partition 相對穩定的使得符合某個條件的元素放在前面

需要標頭檔案<algorithm>

語法描述:sort(begin,end,cmp),cmp引數可以沒有,如果沒有預設非降序排序。

以int為例的基本資料型別的sort使用

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
    int a[5]={1,3,4,2,5};
    sort(a,a+5);
    for(int i=0;i<5;i++)
            cout<<a[i]<<' ';
    return 0;
 }     

因為沒有cmp引數,預設為非降序排序,結果為:

1 2 3 4 5

若設計為非升序排序,則cmp函式的編寫:

bool cmp(int a,int b)

{

  return a>b;

}