写的很丑的字典树。听王大神的话 需要改进。
#include<stdio.h> #include<string.h> #include<math.h> #include<algorithm> using namespace std; struct nn { int zero; int one; }node[320005]; int findd[35]; int main() { int sb; scanf("%d", &sb); while (sb--) { int n, i, j, ii, t, tot; scanf("%d", &n); char s[10]; int ff; for (i = 0; i<320002; i++) { node[i].zero = -1; node[i].one = -1; } int jiedian = 1; for (i = 0; i<n; i++) { scanf("%s", s); if (strcmp("insert", s) == 0) { tot = 0; scanf("%d", &t); while (t) { findd[tot] = t % 2; t = t / 2; tot++; } while (1) { if (tot == 31) break; findd[tot] = 0; tot++; } int bianli = 0; for (ii = 30; ii >= 0; ii--) { if (findd[ii] == 0) { if (node[bianli].zero == -1) { node[bianli].zero = jiedian; jiedian++; } bianli = node[bianli].zero; } else if (findd[ii] == 1) { if (node[bianli].one == -1) { node[bianli].one = jiedian; jiedian++; } bianli = node[bianli].one; } } } else if (strcmp("qmin", s) == 0) { scanf("%d", &t); tot = 0; while (t) { findd[tot] = t % 2; t = t / 2; tot++; } while (1) { if (tot == 31) break; findd[tot] = 0; tot++; } int bianli = 0; int anss = 0; for (ii = 30; ii >= 0; ii--) { if (findd[ii] == 1) { if (node[bianli].one != -1) { anss = anss + 0; bianli = node[bianli].one; } else if (node[bianli].zero != -1) { anss = anss + (1 << ii); bianli = node[bianli].zero; } } else if (findd[ii] == 0) { if (node[bianli].zero != -1) { anss = anss + 0; bianli = node[bianli].zero; } else if (node[bianli].one != -1) { anss = anss + (1 << ii); bianli = node[bianli].one; } } } printf("%d\n", anss); } else if (strcmp("qmax", s) == 0) { scanf("%d", &t); tot = 0; while (t) { findd[tot] = t % 2; t = t / 2; tot++; } while (1) { if (tot == 31) break; findd[tot] = 0; tot++; } int bianli = 0; int anss = 0; for (ii = 30; ii >= 0; ii--) { if (findd[ii] == 1) { if (node[bianli].zero != -1) { anss = anss + (1 << ii); bianli = node[bianli].zero; } else if (node[bianli].one != -1) { anss = anss + 0; bianli = node[bianli].one; } } else if (findd[ii] == 0) { if (node[bianli].one != -1) { anss = anss + (1 << ii); bianli = node[bianli].one; } else if (node[bianli].zero != -1) { anss = anss + 0; bianli = node[bianli].zero; } } } printf("%d\n", anss); } } } return 0; }
时间: 2024-10-28 20:04:59