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
| #include <stdio.h> #include <string.h> #include <algorithm> #include <vector> using namespace std;
const int MAX = 100010; int nXor[MAX]; bool bVis[MAX]; int nFirst[MAX]; struct Edge { int nE; int nW; int nNext; }; Edge egs[MAX * 2];
struct Node { Node* pSons[2]; }; Node nodes[MAX * 32]; Node* pRoot = nodes[0]; int nNew;
void GetBCode(int nL, int* nBCode, int nLen) { nLen = 0; while (nLen <= 30) { nBCode[nLen++] = nL % 2; nL >>= 1; } reverse(nBCode, nBCode + nLen); }
void Insert(int nL) { int nLen = 0; int i = 0; int nBCode[32];
GetBCode(nL, nBCode, nLen); Node* pNode = pRoot;
while (i < nLen) { if (pNode->pSons[nBCode[i]]) { pNode = pNode->pSons[nBCode[i]]; } else { memset(nodes + nNew, 0, sizeof(nodes[nNew])); pNode->pSons[nBCode[i]] = nodes + nNew; pNode = nodes + nNew; ++nNew; } ++i; } }
int FindMax(int nL) { int nLen = 0; int nAns = 0; int i = 0; int nBCode[32]; Node* pNode = pRoot;
GetBCode(nL, nBCode, nLen); while (i < nLen) { int nBest = (nBCode[i] == 0 ? 1 : 0); int nBad = (nBCode[i] == 0 ? 0 : 1); if (pNode->pSons[nBest]) { nAns = 2 * nAns + nBest; pNode = pNode->pSons[nBest]; } else if (pNode->pSons[nBad]) { nAns = 2 * nAns + nBad; pNode = pNode->pSons[nBad]; } else break; ++i; }
return nAns ^ nL; }
void Dfs(int nV, int nL) { nXor[nV] = nL; bVis[nV] = true; for (int e = nFirst[nV]; e != -1; e = egs[e].nNext) { if (!bVis[egs[e].nE]) { Dfs(egs[e].nE, nL ^ egs[e].nW); } } }
int main() { int nN; int nU, nV, nW;
while (scanf("%d", &nN) == 1) { for (int i = 0; i < nN; ++i) nFirst[i] = -1; for (int i = 1, j = 0; i < nN; ++i) { scanf("%d%d%d", &nU, &nV, &nW); egs[j].nE = nV; egs[j].nW = nW; egs[j].nNext = nFirst[nU]; nFirst[nU] = j++; egs[j].nE = nU; egs[j].nW = nW; egs[j].nNext = nFirst[nV]; nFirst[nV] = j++; }
memset(bVis, false, sizeof(bool) * nN); Dfs(0, 0);
memset(nodes[0], 0, sizeof(Node)); nNew = 1; int nAns = 0;
for (int i = 0; i < nN; ++i) { nAns = max(nAns, FindMax(nXor[i])); Insert(nXor[i]); } printf("%d\n", nAns); }
return 0; }
|