= =吃的好饱,明天再写吧= =
#include <stdio.h> #include <string.h> #define N 10001 char str[N][201], count[N]; int left[N] = {0}, right[N] = {0}, size[N] = {0}; int root = 0, last = 0; void left_rotate(int *t) { int k = right[*t]; right[*t] = left[k]; left[k] = *t; size[k] = size[*t]; size[*t] = size[left[*t]] + size[right[*t]]; *t = k; } void right_rotate(int *t) { int k = left[*t]; left[*t] = right[k]; right[k] = *t; size[k] = size[*t]; size[*t] = size[left[*t]] + size[right[*t]]; *t = k; } void sbt_maintain(int *t, int flags) { if (flags) { if (size[left[left[*t]]] > size[right[*t]]) right_rotate(t); else if (size[right[left[*t]]] > size[right[*t]]) { left_rotate(&left[*t]); right_rotate(t); } else return; } else { if (size[right[right[*t]]] > size[left[*t]]) left_rotate(t); else if (size[left[right[*t]]] > size[left[*t]]) { right_rotate(&right[*t]); left_rotate(t); } else return; } sbt_maintain(&left[*t], 0); sbt_maintain(&right[*t], 1); sbt_maintain(t, 0); sbt_maintain(t, 1); } int sbt_search(int t, char *s) { int res; if (t == 0) return 0; if ((res = strcmp(s, str[t])) == 0) return t; return sbt_search(res < 0 ? left[t] : right[t], s); } int sbt_insert(int *t, char *s) { int res = 0, ret; if (*t == 0) { ++last; strcpy(str[last], s); *t = last; ret = *t; count[*t] = 1; } else { ++size[*t]; ret = sbt_insert((res = strcmp(s, str[*t]) < 0) ? &left[*t] : &right[*t], s); } sbt_maintain(t, !res); return ret; } int sbt_remove(int *t, char *s) { int cnt = 0; if (*t != 0) { int res = strcmp(s, str[*t]); if (res == 0) { *t = size[left[*t]] > size[right[*t]] ? left[*t] : right[*t]; ++cnt; } cnt += sbt_remove(&left[*t], s); cnt += sbt_remove(&right[*t], s); } return cnt; } int main(void) { int n, ret; (void)(scanf("%d", &n) == 1); while (n--) { char s[201]; (void)(scanf("%s", s) == 1); if ((ret = sbt_search(root, s)) != 0) ++count[ret]; else sbt_insert(&root, s); } for (n = 1; n <= last; ++n) { printf("%s %d\n", str[n], count[n]); } return 0; } /* cc: run='!$output <in' */