본문 바로가기
알고리즘-자료구조

[개탱][C][컴공과제][희소행렬의 합구하기][파일 입출력][구조체]

by 개탱 2017. 12. 21.
728x90
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
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
 
typedef struct{
    int row;
    int col;
    int value;
} element;
typedef struct{
    element data[100];
    int rows; // 행의 개수
    int cols; // 열의 개수
    int terms; // 항의 개수
} SparseMatrix;
 
 
int max(int a1, int b2);
int iArray[100][100];
 
SparseMatrix a;
SparseMatrix b;
SparseMatrix c;
int main()
{
    int iCountA, iCountB, iCountC;
    FILE *fp = fopen("input.txt","r");
    if(!fp)
    {
        fp = fopen("input.txt","a");
        fclose(fp);
        fp = fopen("input.txt","r");
    }
 
    fscanf(fp,"%d %d %d"&a.rows, &a.cols, &a.terms);
    for(int i = 0; i < a.terms; i++)
    {
        fscanf(fp,"%d %d %d",&a.data[i].row,&a.data[i].col,&a.data[i].value);
    }
 
    fscanf(fp,"%d %d %d"&b.rows, &b.cols, &b.terms);
    for(int i = 0; i < b.terms; i++)
    {
        fscanf(fp,"%d %d %d",&b.data[i].row,&b.data[i].col,&b.data[i].value);
    }
    fclose(fp);
 
    iCountA = iCountB = iCountC = 0;
 
    while(iCountA != a.terms || iCountB != b.terms)
    {
        if(iCountA != a.terms)
            iArray[a.data[iCountA].row][a.data[iCountA].col] += a.data[iCountA++].value;
        if(iCountB != b.terms)
            iArray[b.data[iCountB].row][b.data[iCountB].col] += b.data[iCountB++].value;
    }
 
    c.rows = max(a.rows, b.rows);
    c.cols = max(a.cols, b.cols);
    c.terms = 0;
    for(int i = 0; i < c.rows; i++)
    {
        for(int j = 0; j < c.cols; j++)
        {
            if(iArray[i][j] != 0)
            {
                c.data[iCountC].row = i;
                c.data[iCountC].col = j;
                c.data[iCountC++].value = iArray[i][j];
                c.terms++;
            }
        }
    }
 
    fp = fopen("output.txt","w");
    for(int i = 0; i < c.terms; i++)
        fprintf(fp,"%d %d %d\n",c.data[i].row, c.data[i].col, c.data[i].value);
}
 
int max(int a, int b)
{
    return ((a) > (b) ? (a) : (b));
}
 
cs

혹여 과제기간은 지났지만 궁금할수도 있는 후배님들을 위해 올려봅니다.




댓글