unionFind.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * Copyright (C) 2020, 2019, 2018, 2017 Girish M
  3. * This program is free software; you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation; either version 3 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this program; if not, write to the Free Software
  15. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  16. * MA 02110-1301, USA.
  17. *
  18. */
  19. #include "common.h"
  20. int *A, N;
  21. int isConnected (int x, int y) {
  22. return (A[x] == A[y]);
  23. }
  24. void createUnion (int x, int y) {
  25. int xid = A[x];
  26. int yid = A[y];
  27. int i;
  28. for (i = 0; i < N; i++) {
  29. if (A[i] == xid)
  30. A[i] = yid;
  31. }
  32. }
  33. int main (int argc, char **argv) {
  34. FILE *fp;
  35. int i, x, y;
  36. /* sanity check of command line arguments */
  37. if (argc < 2)
  38. ERR_MESG ("Usage: ./unionFind networkFileName");
  39. /* Read data from network.txt */
  40. if (NULL == (fp = fopen (argv[1], "r")))
  41. ERR_MESG ("Error Opening file");
  42. fscanf (fp, "%d", &N);
  43. /* initialise the arrays */
  44. if (NULL == (A = Malloc (N, int)))
  45. ERR_MESG("main: out of memory\n");
  46. for (i = 0; i < N; i++)
  47. A[i] = i;
  48. for (i = 0; i < N; i++)
  49. printf ("%d ", A[i]);
  50. printf ("\n");
  51. /* Read and build the network */
  52. while (1) {
  53. int retCount = fscanf (fp, "%d %d", &x , &y);
  54. /* this will break out of the while loop at the last line */
  55. if (retCount != 2) break;
  56. printf ("%d %d\n", x, y);
  57. /* Check if already connected */
  58. if (!isConnected (x, y)) {
  59. /* Create their union */
  60. createUnion(x, y);
  61. for (i = 0; i < N; i++)
  62. printf ("%d ", A[i]);
  63. printf ("\n");
  64. }
  65. }
  66. fclose (fp);
  67. return 0;
  68. }