并查集
int pre[MAXN]; int Find(int pos) { if (pre[pos] == pos) // pre是自己,代表为root节点 return pos; int r = pos; while (r != pre[r]) // 找到节点pos的root r = pre[r]; // 路径压缩 int i = pos; while (i != r) { // 把沿路pos->root沿路的节点的root的pre //全部设置为root int t = pre[i]; pre[i] = r; i = t; } return r; } void Join(int posX, int posY) { // 把两个节点的root设置为同一个 int rootX = Find(posX), rootY = Find(posY); if (rootX != rootY) pre[rootX] = rootY; }