//复数矩阵
//定义
//运算

#include <iostream>
#include <complex>
#include <cstdlib>
#include <iomanip>

using Complex = std::complex<double>;

// 1. 纯粹的 C 风格数据结构定义
struct ComplexMatrix {
    int rows;
    int cols;
    Complex* data; // 核心：使用裸指针管理一维连续内存
};

// 2. 构造函数：手动分配内存并初始化为 0
ComplexMatrix createMatrix(int r, int c) {
    ComplexMatrix mat;
    mat.rows = r;
    mat.cols = c;
    // 使用 new 分配连续内存，并默认初始化为 (0,0)
    mat.data = new Complex[r * c](); 
    return mat;
}

// 3. 析构函数：手动释放内存，防止内存泄漏
void destroyMatrix(ComplexMatrix& mat) {
    if (mat.data != nullptr) {
        delete[] mat.data;
        mat.data = nullptr;
    }
    mat.rows = 0;
    mat.cols = 0;
}

// 4. 元素访问：通过指针算术运算直接定位
inline Complex& getElem(ComplexMatrix& mat, int r, int c) {
    return mat.data[r * mat.cols + c];
}

inline const Complex& getElem(const ComplexMatrix& mat, int r, int c) {
    return mat.data[r * mat.cols + c];
}

// 5. 矩阵乘法 (A * B)
ComplexMatrix matMul(const ComplexMatrix& A, const ComplexMatrix& B) {
    if (A.cols != B.rows) {
        std::cerr << "Error: Dimensions incompatible for multiplication!\n";
        std::exit(1);
    }
    
    ComplexMatrix C = createMatrix(A.rows, B.cols);
    
    // i-k-j 循环顺序优化缓存命中率
    for (int i = 0; i < A.rows; ++i) {
        for (int k = 0; k < A.cols; ++k) {
            Complex a_ik = getElem(A, i, k);
            if (a_ik == Complex(0.0, 0.0)) continue; // 简单剪枝
            
            for (int j = 0; j < B.cols; ++j) {
                getElem(C, i, j) += a_ik * getElem(B, k, j);
            }
        }
    }
    return C;
}

// 6. 标量乘法 (矩阵 * 常数)
ComplexMatrix matScale(const ComplexMatrix& A, double scalar) {
    ComplexMatrix C = createMatrix(A.rows, A.cols);
    int totalSize = A.rows * A.cols;
    for (int i = 0; i < totalSize; ++i) {
        C.data[i] = A.data[i] * scalar;
    }
    return C;
}

// 7. 打印矩阵
void printMatrix(const ComplexMatrix& mat, const char* name) {
    std::cout << "Matrix " << name << " (" << mat.rows << "x" << mat.cols << "):\n";
    for (int r = 0; r < mat.rows; ++r) {
        for (int c = 0; c < mat.cols; ++c) {
            Complex val = getElem(mat, r, c);
            std::cout << std::setw(10) << std::fixed << std::setprecision(2) 
                      << val.real() << std::showpos << val.imag() << "i ";
        }
        std::cout << "\n";
    }
    std::cout << std::noshowpos << "\n";
}
