题意:给出 m 个长度都为 n 的字符串,按照逆序数的大小排序输出;
简单的排序题,逆序数的计算,qsort练习;
求逆序数有好的方法(O(n)),这里直接算也是0MS。
# include <stdio.h> typedef struct { char s[51]; int w, id; }DNA; int m, n; DNA a[101]; int DNA_cmp(const void *x, const void *y) { int tmp = (*(DNA*)x).w - (*(DNA*)y).w; if (tmp < 0) return -1; if ((tmp == 0 && (*(DNA*)x).id < (*(DNA*)y).id)) return -1; return 1; } int compute(char *s) { int i, j, ret; ret = 0; for ( i = 0; i < n; ++i) { for ( j = i + 1; j < n; ++j) if (s[i] > s[j]) ++ret; } return ret; } int main() { int i, j; while (~scanf("%d%d", &n, &m)) { for ( i = 1; i <= m; ++i) { a[i].id = i; scanf("%s", a[i].s); a[i].w = compute(a[i].s); } qsort(a+1, m, sizeof(DNA), DNA_cmp); for ( i = 1; i <= m; ++i) puts(a[i].s); } return 0; }