a528: 大數排序

Tags: big-handle


出處:https://zerojudge.tw/ShowProblem?problemid=a528
提交:https://zerojudge.tw/Submissions?problemid=a528&account=allllllan123456


問題:給你 $N\in[1,999]$ 個整數 $X_i\in(-10^{100}, 10^{100})$,請由小到大印出。


解法:只要先定義好兩個字串如何比較大小 (詳見程式碼) 再把規則丟進內建排序去解即可。另外排序的時候只交換 index 也是個很重要的技巧,在其他需要對複雜資料結構作排序的場合會常常用到。


 1#include <bits/stdc++.h>
 2using namespace std;
 3
 4char str[1000][100];
 5int indeX[1000], len[1000];
 6
 7int main() { ios_base::sync_with_stdio(false); cin.tie(0); // IO 優化
 8    int N;
 9    while (cin >> N) {
10        for (int i=0; i<N; i++) cin >> str[i], indeX[i]=i, len[i]=strlen(str[i]);
11        sort(indeX, indeX+N, [](int a, int b) {
12            if (str[a][0]=='-' && str[b][0]=='-') {
13                int t = len[a] - len[b];
14                if (t) return -t<0;
15                return -strcmp(str[a], str[b])<0;
16            } else if (str[a][0]=='-')
17                return true;
18            else if (str[b][0]=='-')
19                return false;
20            else {
21                int t = len[a] - len[b];
22                if (t) return t<0;
23                return strcmp(str[a], str[b])<0;
24            }
25        });
26        for (int i=0; i<N; i++) puts(str[indeX[i]]);
27    }
28    return 0;
29}

no image