51Nod 1097 拼成最小的数(字符串的排序)
1 #include <iostream> 2 #include <cstring> 3 #include <cstdlib> 4 #include <cstdio> 5 #include <algorithm> 6 7 using namespace std; 8 9 const int MAXN = 1e4 + 10; 10 const int MAXA = 11; 11 12 struct num 13 { 14 char A[MAXA]; // 数据 15 int num; // 值 16 int len; // 长度 17 } Num[MAXN]; 18 19 bool cmp(num a, num b) 20 { 21 // 长度相同则比较大小 22 if (a.len == b.len) 23 { 24 return a.num < b.num; 25 } 26 27 int lenMin = a.len > b.len ? b.len : a.len; 28 29 // 逐位比较 从小到大排 30 for (int i = 0; i < lenMin; i++) 31 { 32 if (a.A[i] != b.A[i]) 33 { 34 return a.A[i] < b.A[i]; 35 } 36 } 37 38 // 一个是另一个的前缀 39 if (a.len > b.len) 40 { 41 int i = 0; 42 while (a.A[lenMin] == a.A[i]) 43 { 44 lenMin++; 45 i++; 46 } 47 if (lenMin == a.len) 48 { 49 return a.A[1] > a.A[0]; 50 } 51 return a.A[lenMin] < a.A[i]; 52 } 53 else 54 { 55 int i = 0; 56 while (b.A[lenMin] == b.A[i]) 57 { 58 lenMin++; 59 i++; 60 } 61 if (lenMin == b.len) 62 { 63 return b.A[1] < b.A[0]; 64 } 65 return !(b.A[lenMin] < b.A[i]); 66 } 67 } 68 69 int main() 70 { 71 72 int N; 73 cin >> N; 74 75 int len = 0; 76 for (int i = 0; i < N; i++) 77 { 78 scanf("%s", Num[i].A); 79 Num[i].num = atoi(Num[i].A); 80 //atoi((string)or(char a[])),将字符串换成整数 81 Num[i].len = strlen(Num[i].A); 82 len += Num[i].len; 83 } 84 sort(Num, Num + N, cmp); 85 int flag = 0; 86 for (int i = 0; i < N; i++) 87 { 88 if (flag + Num[i].len < 1000) 89 { 90 flag += Num[i].len; 91 cout << Num[i].A; 92 } 93 else 94 { 95 for (int j = 0; j < Num[i].len; j++) 96 { 97 cout << Num[i].A[j]; 98 if (++flag == 1000) 99 { 100 cout << endl; 101 flag = Num[i].len - j - 1; 102 printf("%s", Num[i].A + j + 1); 103 break; 104 } 105 } 106 } 107 } 108 cout << endl; 109 return 0; 110 }