1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
| #include<iostream> #include<stdio.h> #include<string> #include<string.h> #include<algorithm> using namespace std; const int MAXN = 100000 + 55; int L[MAXN], R[MAXN], F[MAXN]; int tre[MAXN]; int tot, root; inline void clear() { memset(L, -1, sizeof(L)); memset(R, -1, sizeof(R)); memset(F, -1, sizeof(F)); tot = root = 0; } void insert(int t, int x) { if (tot == 0) { root = ++tot; tre[root] = x; F[root] = root; return; } if (x >= tre[t]) { if (R[t] > 0) { insert(R[t], x); } else { R[t] = ++tot; tre[R[t]] = x; F[R[t]] = t; } } else { if (L[t] > 0) { insert(L[t], x); } else { L[t] = ++tot; tre[L[t]] = x; F[L[t]] = t; } } } void rotate(int x) { if (F[x] == x) return; int fa = F[x]; int zu = F[F[x]]; if (R[fa] == x) { R[fa] = L[x]; F[L[x]] = fa; L[x] = fa; F[fa] = x; if (zu != fa) { if (fa == R[zu]) R[zu] = x; else L[zu] = x; F[x] = zu; } else { F[x] = x; root = x; } } else { L[fa] = R[x]; F[R[x]] = fa; R[x] = fa; F[fa] = x; if (zu != fa) { if (fa == L[zu]) L[zu] = x; else R[zu] = x; F[x] = zu; } else { F[x] = x; root = x; } } } void output(int t) { if (L[t] > 0) { output(L[t]); } if (t != 0) printf("%d\n", tre[t]); if (R[t] > 0) { output(R[t]); } } int find(int t,int x) { if (x == tre[t]) return t; if (R[t]>0 &&x > tre[t]) return find(R[t], x); return find(L[t], x); } void splay(int x) { while (x != root) { rotate(x); } } void delete_splay(int t, int x) { splay(find(t,x)); int del = root; if (L[del] > 0 && R[del] > 0) { int temp = R[del]; root = R[del]; while (L[temp]>0) { temp = L[temp]; } L[temp] = L[del]; F[L[del]] = temp; F[root] = root; tre[del] = 0; L[del] = R[del] = F[del] = -1; return; } else { if (L[root] > 0) { root = L[root]; F[root] = root;tre[del] = 0; L[del] = R[del] = F[del] = -1; return; } else if(R[root]>0) { root = R[root]; F[root] = root;tre[del] = 0; L[del] = R[del] = F[del] = -1; } else { clear(); } } }
int main() { clear(); int n; scanf("%d", &n); tot = 0; root = 0; for (int i = 0; i < n; i++) { int a; scanf("%d", &a); insert(root, a); splay(tot); } delete_splay(root, 2); output(root); }
|