高斯消元法解异或线性方程组

高斯消元法

对于一组线性方程组,枚举每一列进行如下步骤:
1、找到首元非零行
2、将这一行交换到第一行
3、将这一行的第一个数变成1,对当前这一行进行操作,不涉及矩阵的初等变换
4、将下面所有行的当前列全部消成0,利用矩阵的初等变换

对于原异或方程组进行变换后
如果得到的矩阵是一个完美的上三角矩阵,则说明方程组有唯一解
否则会出现两种情况:
1、推出矛盾,即:零==非零,这种情况下表示无解
2、否则,即原异或方程组中有多余的方程,此时有无穷多解

高斯消元解异或线性方程组

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 110;
int n;
int a[N][N];
int gauss()
{
    
    
    int c, r; //c表示枚举的哪一列,r表示枚举的哪一行
    for (c = 0, r = 0; c < n; c++)
    {
    
    
        int t = r; //记录当前列
        for (int i = r; i < n; i++)
        {
    
    
            if (a[i][c])
                {
    
    t = i;break;}
        }
        if (!a[t][c]) continue;
        for (int i = c; i <= n; i++) swap(a[t][i], a[r][i]);
        for (int i = r + 1; i < n; i++)
        {
    
    
            if (a[i][c])
            {
    
    
                for (int j = c; j <=n ; j++)
                    a[i][j] ^= a[r][j];
            }
        }
        r++;
    }
    if (r < n)
    {
    
    
        for (int i = r; i < n; i ++ )
            if (a[i][n])
                return 2;
        return 1;
    }

    for (int i = n - 1; i >= 0; i -- )
        for (int j = i + 1; j < n; j ++ )
            a[i][n] ^= a[i][j] * a[j][n];

    return 0;
}
int main()
{
    
    
    cin >> n;
    for (int i = 0; i < n; i ++ )
        for (int j = 0; j < n + 1; j ++ )
            cin >> a[i][j];
    int t = gauss();
    if (t == 0)
    {
    
    
        for (int i = 0; i < n; i++)
            printf("%d\n", a[i][n]);
    }
    else if (t == 1)
        cout << "Multiple sets of solutions" << endl;
    else
        cout << "No solution" << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_46126537/article/details/112131835