C,C++/DATA STRUCTURE
희소 행렬
너래쟁이
2017. 11. 7. 17:09
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> // 20131885 강보원 int a[100][100]; int r,c,v; // 행, 열, 값 입력 int n,m,s; // 행의개수, 열의개수, 항의개수 입력 typedef struct { int row; int col; int value; } element; typedef struct { element data[100]; int rows; // 행의 개수 int cols; // 열의 개수 int terms; // 항의 개수 } SparseMatrix; // Matrix[0]은 첫번째 희소행렬 Matrix[1]는 두번째 희소행렬 SparseMatrix Matrix[2]; int main() { FILE *in, *out; in = fopen("input.txt", "r"); out = fopen("output.txt", "w"); if (in == NULL) { printf("입력 파일이 없거나 오류가 발생하였습니다\n"); } for (int i = 0; i < 2; i++) // 총 2번 행열의 입력 { // 행의개수, 열의개수, 항의개수 입력 fscanf(in, "%d %d %d", &n, &m, &s); Matrix[i].rows = n; Matrix[i].rows = m; Matrix[i].terms = s; for (int j = 0 ; j < s ; j ++) { // 행, 열, 값 입력 fscanf(in,"%d %d %d", &r, &c, &v); Matrix[i].data[j].row = r; Matrix[i].data[j].col = c; Matrix[i].data[j].value = v; a[r][c] = a[r][c] + v; } } //희소행렬 a와 b의 크기가 같은지 확인 if (Matrix[0].rows != Matrix[1].rows || Matrix[0].cols != Matrix[1].cols) { fprintf(stderr, "희소행렬 크기에러\n"); exit(1); } for (int i = 0 ; i < 100 ; i ++ ) { for (int j = 0 ; j < 100 ; j ++ ) if (a[i][j] != 0) { fprintf(out, "%d %d %d\n", i, j, a[i][j]); } } fclose(in); fclose(out); } | cs |