// Tarjan's off-line least common ancestors // See CLRS, 2nd ed, p.521, problem 21-3 // Assumes order of siblings is irrelevant // BPW 1/12/03 #include #include #define WHITE (0) #define BLACK (1) // Tree structure int n,root,*firstChild,*rightSibling,*treeParent,*color; // P - pairs to find LCA for // Psize = number of pairs // uP = first vertex, vP = second vertex, firstPair[i]=first pair with // i as uP int Psize,*uP,*vP,*firstPair; // Union-find structure for vertices of tree int *parent,*weight,numTrees; // For LCA function int *ancestor; void readTree() { int i,k,kParent; scanf("%d",&n); firstChild=(int*) malloc(n*sizeof(int)); rightSibling=(int*) malloc(n*sizeof(int)); treeParent=(int*) malloc(n*sizeof(int)); color=(int*) malloc(n*sizeof(int)); if (!firstChild || !rightSibling || !treeParent || !color) { printf("malloc failed %d\n",__LINE__); exit(0); } for (i=0;i=n || kParent<0 || kParent>=n || color[k]==WHITE) { printf("Input error %d\n",__LINE__); exit(0); } treeParent[k]=kParent; color[k]=WHITE; rightSibling[k]=firstChild[kParent]; firstChild[kParent]=k; } root=(-1); for (i=0;iweight[j]) { parent[j]=i; weight[i]+=weight[j]; } else { parent[i]=j; weight[j]+=weight[i]; } numTrees--; } void readP() { int i,j; scanf("%d",&Psize); firstPair=(int*) malloc((n+1)*sizeof(int)); uP=(int*) malloc(Psize*sizeof(int)); vP=(int*) malloc(Psize*sizeof(int)); if (!firstPair || !uP || !vP) { printf("malloc failed %d\n",__LINE__); exit(0); } // Pairs {x,y} must be sorted lexicographically // and are expected to be available symmetrically, // i.e. (x,y) and (y,x) for (i=0;iuP[i] || (uP[i-1]==uP[i] && vP[i-1]>vP[i])) { printf("Input order error %d\n",__LINE__); exit(0); } j=0; for (i=0; i