其他分享
首页 > 其他分享> > AcWing 884. 高斯消元解异或线性方程组 题解 (高斯消元)

AcWing 884. 高斯消元解异或线性方程组 题解 (高斯消元)

作者:互联网

#include<iostream>
#include<algorithm>

using namespace std;

const int N = 110;

int n, a[N][N];

int gauss(){
	int r, c;
	for(c = 0, r = 0; c < n; c ++ ){
		int t = r;
		for(int i = t; 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];//原题中是异或,同为1的情况异或后为0,所以进行异或操作
				}
			}
		}
		r ++ ;
	}
	if(r < n){
		for(int i = r; i < n; i ++ ){//遍历r之后的每一行
			if(a[r][n]){//如果这个方程的常数项不为0,就代表这组方程无解
				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];//原题中是异或,同为1的情况异或后为0,所以进行异或操作
		}
	}
	
	return 0;
}

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

标签:return,884,int,题解,原题,++,异或,高斯消
来源: https://blog.csdn.net/qiaodxs/article/details/120302422