/* This program uses code from "Algorithms in C, Third Edition," * by Robert Sedgewick, Addison-Wesley, 1998. */ #include /* Made N smaller, so we can print all ids */ #define N 10 /* returns the set id of the object. */ int find(int object, int id[]) { int next_object; next_object = id[object]; while (next_object != id[next_object]) { id[next_object] = id[id[next_object]]; next_object = id[next_object]; } return next_object; } /* unites the two sets specified by set_id1 and set_id2 */ void set_union(int set_id1, int set_id2, int id[], int sz[]) { if (sz[set_id1] < sz[set_id2]) { id[set_id1] = set_id2; sz[set_id2] += sz[set_id1]; } else { id[set_id2] = set_id1; sz[set_id1] += sz[set_id2]; } } main() { int p, q, i, id[N], sz[N], p_id, q_id; for (i = 0; i < N; i++) { id[i] = i; sz[i] = 1; } while (scanf("%d %d", &p, &q) == 2) { p_id = find(p, id); q_id = find(q, id); if (p_id == q_id) { printf(" %d and %d were on the same set\n", p, q); continue; } set_union(p_id, q_id, id, sz); printf(" %d %d link led to set union\n", p, q); for (i = 0; i < N; i++) { // printf(" id[%d] = %d\n", i, id[i]); } } }