# Untitled

??
unknown
c_cpp
2 years ago
2.6 kB
4
Indexable
Never
```#include <bits/stdc++.h>

using namespace std;

int n;
vector<vector<double>> eyes(int n){
// n : size
vector<vector<double>> ret;
ret.resize(n+1,vector<double>(n+1,0));
for(int i =1;i<=n;i++){
ret[i][i]=1;
}
return ret;
}

void Input(vector<vector<double>> & matrix, int & n){
for(int i = 1;i<=n;i++){
for(int j =1;j<=n;j++){
cin >> matrix[i][j];
}
}
return;
}
void Print(vector<vector<double>> & matrix, int n){
cout << fixed; cout.precision(3);
for(int i = 1; i<=n;i++){
for(int j = 1; j<=n; j++){
cout << matrix[i][j] << " ";
}
cout << '\n';
}
}
vector<vector<double>> matmul(vector<vector<double>> & A, vector<vector<double>> & B, int size) // AB
{
vector<vector<double>> ret (n+1, vector<double>(n+1,0));
for(int i = 1;i<=n;i++){
for(int j = 1; j<=n;j++){
for(int l = 1;l<=n;l++){
ret[i][j] += A[i][l] * B[l][j];
}
}
}
return ret;
}

void gaussian(vector<vector<double>> & A, int n){
vector<vector<double>> I = eyes(n);
vector<vector<double>> P = eyes(n);

for (int i = 1;i<=n;i++){
// row calculation
// with A, and I
// largest
double pivot = abs(A[i][i]);
int index = i;
for(int k = i+1;k<=n;k++){
if(abs(A[k][i])>pivot){
index = k;
pivot = abs(A[k][i]);
}
}
// cout << index << " " << i <<'\n';
// 이미 돌려주고 있음. -> 틀렸음.
if(pivot== (double)0){
cout << -1 <<'\n';
return;
}

if(index!=i){
for(int k = i;k<=n;k++){
swap(A[index][k],A[i][k]);
}
for(int k = 1;k<=n;k++){
swap(P[index][k],P[i][k]);
}
}

// gaussian elimination with L
pivot = A[i][i];
for(int j = i+1;j<=n;j++){
double multi = A[j][i]/(pivot);
I[j][i] += multi;
for(int l = i;l<=n;l++){
A[j][l] -= multi * A[i][l];
}
}
}
// Print(P,n);
vector<vector<double>> L = matmul(P,I, n);
// vector<vector<double>> ret = matmul(L,A, n);
Print(L,n);
Print(A,n);
return;
}

int main(void){
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
cin >> n;
vector<vector<double>> matrix(n+1, vector<double>(n+1,(double)0));
Input(matrix, n); // ok
gaussian(matrix,n);
}c```