Skip to content

E19942: 二维矩阵上的卷积运算

matrices, http://cs101.openjudge.cn/pctbook/E19942/

思路:定义一个卷积函数即可,一遍ac,用时约15min

cpp
#include <iostream>
#include <map>
#include <vector>
#include <sstream>
using namespace std;


class marix
{
    private:
        int index = 0;//用来表征能否进行运算

    public:
        int row, col;
        vector<vector<int>> mar;

        void setSize()
        {
            cin >> row >> col;
            mar.resize(row, vector<int>(col, 0));
        }

        void getMarix()
        {
            for(int i = 0; i < row; i++)
            {
                for(int j = 0; j < col; j++)
                {
                    cin >> mar[i][j];
                }
            }
            index = 0;
        }

        void printMarix()
        {
            if(index == 1)
                cout << "Error!" ;
            else
            {
                for(int i = 0; i < row; i++)
                {
                    if (i) cout << endl;
                    for(int j = 0; j < col; j++)
                    {
                        if (j) cout << " ";
                        cout << mar[i][j] ;
                    } 
                }
            }
        }

};

marix convolution(marix A, marix B)
{
    marix C;
    C.row = A.row - B.row + 1;
    C.col = A.col - B.col + 1;
    C.mar.resize(C.row, vector<int>(C.col, 0));
    for(int i = 0; i < C.row; i++)
    {
        for(int j = 0; j < C.col; j++)
        {
            for(int k = 0; k < B.row; k++)
            {
                for(int l = 0; l < B.col; l++)
                {
                    C.mar[i][j] += A.mar[i + k][j + l] * B.mar[k][l];
                }
            }
        }
    }
    return C;
}

int main() 
{
    marix A, B, C;
    A.setSize();
    B.setSize();
    A.getMarix();
    B.getMarix();
    C = convolution(A, B);
    C.printMarix();
}