Problem:A list of non negative integers will be provided, arrange the numbers in such a way that they form the largest number possible.
Example:
From a list : 9 30 31 4 10 ; Largest number formed : 94313010.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
#include <stdio.h> #include <algorithm> #include <vector> #include <iostream> #include <string> using namespace std; //vector<string> vb; string vb[105]; int n; bool cmp(string a,string b) { string p=a; p.append(b); string q=b; q.append(a); for(int i=0;i<p.size();i++) { if((p[i]-'0')<(q[i]-'0')) return 1;//if a<b if((p[i]-'0')>(q[i]-'0')) return 0;//if b<a } return 1; } void _sort() { string tmp; for(int i=0;i<n;i++) { for(int j=0;j<n-1;j++) { if(cmp(vb[j],vb[j+1])==0) { tmp=vb[j]; vb[j]=vb[j+1]; vb[j+1]=tmp; } } } } int main() { //code int t,a; string crnt,prev; scanf("%d",&t); while(t--) { scanf("%d",&n); for(int i=0;i<n;i++) { scanf("%d",&a); prev=""; if(a==0) prev.append(1u,'0'); else { prev=""; crnt=""; while(a) { crnt.append(1u,(a%10)+'0'); a/=10; crnt.append(prev); prev=crnt; crnt=""; } } vb[i]=prev; } _sort(); for(int i=n-1;i>=0;i--) cout<<vb[i]; cout<<"\n"; } return 0; } |