Acwing--- 884. 高斯消元解异或线性方程组 (Java)_数学知识_高斯消元模板

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

原题链接

①. 题目

在这里插入图片描述在这里插入图片描述

②. 思路

  • 这题流程高斯消元差不多,里面只有1和0两个数,异或运算相同为0,不同为1,任何数与0异或 0 ^ n = n,那就简单了,和线性方程解一样

左下角消0

  1. 枚举列
  2. 找第一个非零行
  3. 交换
  4. 把同列下面行消零(异或)

判断3种情况

  1. r=n,唯一解
  2. r<n,行数没有到达最后一行 说明最后几行存在全为0
  3. 最后一位不为0 无解
  4. 最后一位为0 无穷多解

③. 学习点

④. 代码实现

import java.util.Scanner;

public class Main {
    
    
	static int n;
	static int a[][]=new int[110][110];
	public static void main(String[] args) {
    
    
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		for (int i = 0; i <n; i++) {
    
    
			for (int j = 0; j <=n; j++) {
    
    
				a[i][j]=sc.nextInt();
			}
		}
		int t=gauss();
		if(t==0) {
    
    
			for (int i = 0; i <n; i++) {
    
    
				System.out.println(a[i][n]);
			}
		}else if(t==1) {
    
    
			System.out.println("No solution");
		}else {
    
    
			System.out.println("Multiple sets of solutions");
		}
	}
	
	static int gauss() {
    
    
		int c=0,r=0;
		for (; c <n; c++) {
    
    
			//在该列找出最大值1的行号
			int t=r;
			for (int i = r; i <n; i++) {
    
    
				if(a[i][c]!=0) {
    
    
					t=i;
					break;
				}
			}
			//当前列都是0就跳过
			if(a[t][c]==0) {
    
    
				continue;
			}
			//找到当前最大值的行 交换上面未固定的行
			//遍历每一列进行交换 r表示最顶上的那一行 t表示当前最大值的那一行
			for (int i =c; i <=n; i++) {
    
    
				int q=a[r][i];
				a[r][i]=a[t][i];
				a[t][i]=q;
			}
			
			//将第c列最大值下面的数全部变成0
			for (int i =r+1; i <n; i++) {
    
    
				if(a[i][c]!=0) {
    
    
					//将下面为1的列和当前最大值的列每一个数进行异或运算
					for (int j =c; j <=n; j++) {
    
    
						a[i][j]^=a[r][j];
					}
				}
			}
			r++;
		}
		//行数没有到达最后一行 说明最后几行存在全为0
		if(r<n) {
    
    
			for (int i =r; i <n; i++) {
    
    
				if(a[i][n]!=0) {
    
    //最后一位不为0 无解
					return 2;
				}
			}
			return 1;
		}
		//唯一解从下往上推导 r=n
		for (int i =r-1; i >=0; i--) {
    
    
			for (int j = i+1; j <n; j++) {
    
    
				//消除上面的1 使用&进行运算  
				a[i][n]^=a[i][j]&a[j][n];//只有1或0,所以*和&一样 
			}
		}
		return 0;
	}
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45480785/article/details/113896483