打个酱油~
#include<stdio.h> #include<stdlib.h> typedef struct path{ int node; struct path * pre; }PATH; typedef struct{ int left, right; }GRAGH; int cmp(const void * a, const void * b) { return *(int *)a - *(int *)b; } int cal(int * a, int n) { GRAGH * g; PATH * p, * tp; int * m, * s, pn, c = 0, i, j, k, t; g = (GRAGH *)malloc(n * (sizeof(GRAGH) + sizeof(PATH) + sizeof(int) * 2)); p = (PATH *)&g[n]; m = (int *)&p[n]; s = (int *)&m[n]; qsort(a, n, sizeof(int), cmp); for(i = 0; i < n; i++) { for(j = -1, k = i - 1; j < k; a[t] > a[i] / 3 ? (k = t - 1) : (j = t)) t = (j + k + 1) >> 1; g[i].left = k; for(j = i + 1, k = n; j < k; a[t] < a[i] * 3 ? (j = t + 1) : (k = t)) t = (j + k) >> 1; g[i].right = j; } for(i = 0; i < n; m[i++] = -1); p[0].pre = NULL; for(i = 0; i < n; i++) { if(m[i] != -1) continue; p[0].node = i; pn = 1; for(j = 0; j < n; s[j++] = 0); s[i] = 1; for(j = 0; j < pn; j++) { for(k = g[p[j].node].left; k >= 0 && m[k] != -1; k--) { if(s[k]) continue; p[pn].node = m[k]; p[pn++].pre = &p[j]; s[k] = s[m[k]] = 1; } if(k >= 0) break; for(k = g[p[j].node].right; k < n && m[k] != -1; k++) { if(s[k]) continue; p[pn].node = m[k]; p[pn++].pre = &p[j]; s[k] = s[m[k]] = 1; } if(k < n) break; } if(j < pn) for(c++, tp = &p[j]; tp; tp = tp->pre) { m[k] = tp->node; t = m[tp->node]; m[tp->node] = k; k = t; } } /*output for test*/ for(i = 0; i < n; i++) { if(m[i] == i) continue; if(m[i] == -1){ printf("(%d)\n", a[i]); continue;} printf("(%d,%d)\n", a[i], a[m[i]]); m[m[i]] = m[i]; m[i] = i; } /*test end*/ free(g); return n - c; } int main() { int * a, n, i; scanf("%d", &n); a = (int *)malloc(n * sizeof(int)); for(i = 0; i < n; scanf("%d", &a[i++])); printf("%d\n", cal(a, n)); free(a); return 0; }