c programming - exercise f

Download C Programming - Exercise F

If you can't read please download the document

Upload: theo

Post on 17-Dec-2015

4 views

Category:

Documents


1 download

DESCRIPTION

C Programming - Exercise F

TRANSCRIPT

//Exercize F#include #include int main (void) {int i = 0, j = 0, n = 0, minw = 0, ipos = 0, jpos = 0, k = 0, m = 0, flag = 1, sum = 0;int* A = NULL, *B = NULL, *t = NULL, *y = NULL;int **connection = NULL, **weight = NULL;printf("How many tops are there? ");scanf(" %d", &n);while (n % 2 == 1) {printf("The number of tops must be an even one. Type it again: ");scanf(" %d", &n);}connection = calloc(n, sizeof(int*));weight = calloc(n, sizeof(int*));A = calloc(n/2, sizeof(int));B = calloc(n/2, sizeof(int));t = calloc(n, sizeof(int));y = calloc(n, sizeof(int));//Input for connection and weightfor (; i < n; i++) {printf("How many tops are connected with top %d? ", i);scanf(" %d", &t[i]);printf("Type them followed by their weights separated with spaces: ");connection[i] = calloc(t[i] , sizeof(int));weight[i] = calloc(t[i] , sizeof(int));for (j = 0; j < t[i]; j++) {scanf(" %d", &connection[i][j]);scanf(" %d", &weight[i][j]);}for(j = 0; j < t[i]; j++) {while(connection[i][j] < 0 || connection[i][j] >= n) {printf("Top %d does not exist. Please type it again (alone): ", connection[i][j]);scanf(" %d", &connection[i][j]);}}}//Creation of A and Bminw = 9999;while (1){for (i = 0; i < n; i++) {for (j = 0; j < t[i]; j++) {for (m = 0; m < k; m++)if (connection[i][j] == A[m] || connection[i][j] == B[m]) {break;}if (m >= k && weight[i][j] < minw) {minw = weight[i][j];ipos = i;jpos = j;flag = 1;}}}if (flag){A[k] = connection[ipos][jpos];B[k] = ipos;sum += weight[ipos][jpos];free(weight[B[k]]);free(weight[A[k]]);free(connection[B[k]]);free(connection[A[k]]);k++;flag = 0;minw = 9999;} elsebreak;}////Results outputprintf("\n\nA = [");for (m = 0; m < k; m++){printf("%d ", A[m]);}printf("\b]\n");printf("B = [");for (m = 0; m < k; m++){printf("%d ", B[m]);}printf("\b]");printf("\n\nThe sum of the connections between the tops of A and B is %d.\n\n", sum);for (m = 0; m < k; m++) {y[A[m]] = 1;y[B[m]] = 1;}for (m = 0; m < n; m++) {if (!y[m]) {printf("The top %d doesn't have a pair! :(\n\n", m);free(weight[y[m]]);free(connection[y[m]]);}}free(connection);free(weight);free(t);free(y);free(A);free(B);return 0;}