123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- /*
- * Copyright (C) 2020, 2019, 2018, 2017 Girish M
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
- * MA 02110-1301, USA.
- *
- */
- #include "common.h"
- int *A, N;
- int isConnected (int x, int y) {
- return (A[x] == A[y]);
- }
- void createUnion (int x, int y) {
- int xid = A[x];
- int yid = A[y];
- int i;
- for (i = 0; i < N; i++) {
- if (A[i] == xid)
- A[i] = yid;
- }
- }
- int main (int argc, char **argv) {
- FILE *fp;
- int i, x, y;
- /* sanity check of command line arguments */
- if (argc < 2)
- ERR_MESG ("Usage: ./unionFind networkFileName");
- /* Read data from network.txt */
- if (NULL == (fp = fopen (argv[1], "r")))
- ERR_MESG ("Error Opening file");
- fscanf (fp, "%d", &N);
- /* initialise the arrays */
- if (NULL == (A = Malloc (N, int)))
- ERR_MESG("main: out of memory\n");
- for (i = 0; i < N; i++)
- A[i] = i;
- for (i = 0; i < N; i++)
- printf ("%d ", A[i]);
- printf ("\n");
-
- /* Read and build the network */
- while (1) {
- int retCount = fscanf (fp, "%d %d", &x , &y);
- /* this will break out of the while loop at the last line */
- if (retCount != 2) break;
- printf ("%d %d\n", x, y);
- /* Check if already connected */
- if (!isConnected (x, y)) {
- /* Create their union */
- createUnion(x, y);
- for (i = 0; i < N; i++)
- printf ("%d ", A[i]);
- printf ("\n");
- }
- }
- fclose (fp);
- return 0;
- }
|