poj1222 EXTENDED LIGHTS OUT (高斯消元)

本文介绍了一种使用高斯消元法解决经典Lights Out游戏的方法。通过构建30×30的方程组,利用矩阵运算求解按钮按压状态,实现游戏全灭灯的目标。
EXTENDED LIGHTS OUT
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 9270 Accepted: 6019

Description

In an extended version of the game Lights Out, is a puzzle with 5 rows of 6 buttons each (the actual puzzle has 5 rows of 5 buttons each). Each button has a light. When a button is pressed, that button and each of its (up to four) neighbors above, below, right and left, has the state of its light reversed. (If on, the light is turned off; if off, the light is turned on.) Buttons in the corners change the state of 3 buttons; buttons on an edge change the state of 4 buttons and other buttons change the state of 5. For example, if the buttons marked X on the left below were to be pressed,the display would change to the image on the right. 

The aim of the game is, starting from any initial set of lights on in the display, to press buttons to get the display to a state where all lights are off. When adjacent buttons are pressed, the action of one button can undo the effect of another. For instance, in the display below, pressing buttons marked X in the left display results in the right display.Note that the buttons in row 2 column 3 and row 2 column 5 both change the state of the button in row 2 column 4,so that, in the end, its state is unchanged. 

Note: 
1. It does not matter what order the buttons are pressed. 
2. If a button is pressed a second time, it exactly cancels the effect of the first press, so no button ever need be pressed more than once. 
3. As illustrated in the second diagram, all the lights in the first row may be turned off, by pressing the corresponding buttons in the second row. By repeating this process in each row, all the lights in the first 
four rows may be turned out. Similarly, by pressing buttons in columns 2, 3 ?, all lights in the first 5 columns may be turned off. 
Write a program to solve the puzzle.

Input

The first line of the input is a positive integer n which is the number of puzzles that follow. Each puzzle will be five lines, each of which has six 0 or 1 separated by one or more spaces. A 0 indicates that the light is off, while a 1 indicates that the light is on initially.

Output

For each puzzle, the output consists of a line with the string: "PUZZLE #m", where m is the index of the puzzle in the input file. Following that line, is a puzzle-like display (in the same format as the input) . In this case, 1's indicate buttons that must be pressed to solve the puzzle, while 0 indicate buttons, which are not pressed. There should be exactly one space between each 0 or 1 in the output puzzle-like display.

Sample Input

2
0 1 1 0 1 0
1 0 0 1 1 1
0 0 1 0 0 1
1 0 0 1 0 1
0 1 1 1 0 0
0 0 1 0 1 0
1 0 1 0 1 1
0 0 1 0 1 1
1 0 1 1 0 0
0 1 0 1 0 0

Sample Output

PUZZLE #1
1 0 1 0 0 1
1 1 0 1 0 1
0 0 1 0 1 1
1 0 0 1 0 0
0 1 0 0 0 0
PUZZLE #2
1 0 0 1 1 1
1 1 0 0 0 0
0 0 0 1 0 0
1 1 0 1 0 1
1 0 1 1 0 1
题目大意:经典的开关灯问题(自行百度)。
解题思路:方法一:用搜索勉强可以卡过去,用二进制压缩枚举第一行的状态......
方法二:高斯消元
0ms就A了。
问题是要怎么构造矩阵呢。大家的思路一样,我就不打了,复制别人的2333.
摘自 http://www.cnblogs.com/devtang/archive/2012/07/24/2606728.html

这题分析如下:未知数共30个,因为30个灯的状态我们都必须要确定下来才能解决这道题。

比如说(1,1)这个灯的最终状态将由(1,1),(1,2),(2,1)这三个灯的状态决定这样就可以列出一个方程:

(l(1,1)+x(1,1)+x(1,2)+0*x(1,3)+...+x(2,1)+...)%2=0(l表示给出的初始状态的矩阵,x表示最终需要求的开关矩阵),再比如说对于(1,2)这个灯的状态又可列出一个方程:

(l(1,2)+x(1,1)+x(1,2)+x(1,3)+...+x(2,2)+...)%2=0这样对于30个位置我们可以列出30个方程(不相关),共有30个未知数,故方程一定有唯一解。

现在就我来说吧,2333,矩阵构造完,把l(x,y)这个常数项移到右边去。

因为是(mod2)的,所以用一下exgcd求一下同余方程就可以了

MOD2跟MOD7原理一样。

加注释的代码如下:

#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream> 
#include<algorithm> 
using namespace std;
const int maxn=40,n=30,m=30,MOD=2;
int x,y,cas=1;
double matrix[maxn][maxn],mp[maxn][maxn];
int gcd(int a,int b){return b==0?a:gcd(b,a%b);}
bool pd(double x,double y)//判断是否越界
{
	if(x<0||x>=5||y<0||y>=6)return false;
	return true;
}
void initmatrix()
{
	for(int i=0;i<5;i++)for(int j=0;j<6;j++)scanf("%lf",&mp[i][j]);
	for(int i=0;i<30;i++)//30个位置,30个变量 
	{
		for(int j=0;j<30;j++)matrix[i][j]=0;//矩阵初始化 
		int a,b,c,d;//上下左右 
		int row=i/6,col=i-row*6;
		matrix[i][i]=1;//当前位置 
		matrix[i][m]=mp[row][col];
		a=i-6;if(pd(row-1,col))matrix[i][a]=1;//上 
		b=i+6;if(pd(row+1,col))matrix[i][b]=1;//下
		c=i-1;if(pd(row,col-1))matrix[i][c]=1;//左 
		d=i+1;if(pd(row,col+1))matrix[i][d]=1;//右
	}
}
int exgcd(int m,int& x,int n,int& y)//exgcd求同余方程 
{
	int x1=0,y1=1,x0=1,y0=0,r=(m%n+n)%n,q=(m-r)/n;x=0,y=1;
	while(r)x=x0-q*x1,y=y0-q*y1,x0=x1,y0=y1,x1=x,y1=y,m=n,n=r,r=m%n,q=(m-r)/n;
	return n;
}
void presolve()
{
	for(int i=0;i<n;i++)//用第i行对其他行进行逐步消元 
	{
		int maxrow=i;
		for(int j=i+1;j<n;j++)if(fabs(matrix[j][i])>fabs(matrix[maxrow][i]))maxrow=j;
		if(maxrow!=i)for(int j=0;j<=m;j++)swap(matrix[i][j],matrix[maxrow][j]);
		if(matrix[i][i]==0)continue;
		for(int k=i+1;k<n;k++)//对k行进行消元 
		{
			double f=matrix[k][i]/matrix[i][i]; 
			for(int j=i;j<=m;j++)
			{
				matrix[k][j]-=f*matrix[i][j];
				matrix[k][j]=((int)matrix[k][j]%MOD+MOD)%MOD;
			} 
		}
	}
}
void cal()
{
	for(int i=n-1;i>=0;i--)
	{
		double ans=0;
		for(int j=i+1;j<n;j++)
		{
			ans+=matrix[j][m]*matrix[i][j];
			matrix[i][m]-=matrix[j][m]*matrix[i][j];
			matrix[i][m]=((int)matrix[i][m]%MOD+MOD)%MOD;
		}
		int M=exgcd((int)matrix[i][i],x,MOD,y);
		x=x*matrix[i][m]/M;
		x=(x%(MOD/M)+MOD/M)%(MOD/M);
		matrix[i][m]=x;
	}
}
void output()
{
	int id=0;
	printf("PUZZLE #%d\n",cas++);
	for(int i=0;i<5;i++)
	{
		for(int j=0;j<6;j++)printf("%s%.0lf",j?" ":"",matrix[id++][30]);
		printf("\n");
	}
}
int main()
{
	int T;
	scanf("%d",&T);
	while(T--)initmatrix(),presolve(),cal(),output();
}


MATLAB主动噪声和振动控制算法——对较大的次级路径变化具有鲁棒性内容概要:本文主要介绍了一种在MATLAB环境下实现的主动噪声和振动控制算法,该算法针对较大的次级路径变化具有较强的鲁棒性。文中详细阐述了算法的设计原理与实现方法,重点解决了传统控制系统中因次级路径动态变化导致性能下降的问题。通过引入自适应机制和鲁棒控制策略,提升了系统在复杂环境下的稳定性和控制精度,适用于需要高精度噪声与振动抑制的实际工程场景。此外,文档还列举了多个MATLAB仿真实例及相关科研技术服务内容,涵盖信号处理、智能优化、机器学习等多个交叉领域。; 适合人群:具备一定MATLAB编程基础和控制系统理论知识的科研人员及工程技术人员,尤其适合从事噪声与振动控制、信号处理、自动化等相关领域的研究生和工程师。; 使用场景及目标:①应用于汽车、航空航天、精密仪器等对噪声和振动敏感的工业领域;②用于提升现有主动控制系统对参数变化的适应能力;③为相关科研项目提供算法验证与仿真平台支持; 阅读建议:建议读者结合提供的MATLAB代码进行仿真实验,深入理解算法在不同次级路径条件下的响应特性,并可通过调整控制参数进一步探究其鲁棒性边界。同时可参考文档中列出的相关技术案例拓展应用场景。
### 矩阵在扩展版 Lights Out 游戏中的实现 #### 背景介绍 关灯游戏(Lights Out)是一种基于逻辑的益智游戏,其核心机制涉及通过一系列操作使所有灯光熄灭。该游戏可以通过线性代数的方法建模并求解,其中矩阵扮演了重要角色。具体来说,游戏的状态可以用二进制向量表示,而每次点击的操作可以看作是对当前状态施加的一个变换。 对于扩展版本的游戏(如 POJ 1222),通常是一个 \( M \times N \) 的网格,初始状态下某些位置可能亮起或熄灭。目标是找到一种最小化翻转次数的方式使得整个网格变为全零状态(即所有灯均关闭)。这一过程可通过构建一个对应的布尔方程组来描述,并利用高斯消法或其他数值技术求解[^3]。 #### 数学模型建立 假设我们有一个大小为 \( m=5, n=6 \) 的棋盘,则总共有 30 个独立变量代表各个格子是否被按压过。设这些未知数构成列向量 \( x=[x_1,x_2,...,x_{30}]^T \),如果某位 i 对应的位置需要按下一次就令 xi=1 否则等于 0 。接着定义另一个长度相同的响应矢量 y ,它记录的是最终期望达到的目标配置 —— 这里就是全是 'off' 或者说都是 0 值的情况下的布局图样 [y₁,y₂,…,yn]=₀₆₀⁰[^4]. 为了表达上述关系,我们需要创建一个系数矩阵 A 来捕捉每一个按钮动作如何影响周围邻居节点的变化情况: \[ Ax = b \] 这里, - **A** 是一个稀疏矩阵,每一行对应于某个特定单格及其邻域的影响模式; - **b** 表示初始条件下的光源分布状况; - 解决这个系统意味着寻找合适的输入序列 x 以满足给定的要求 b. 由于涉及到异或运算特性(xor operation), 实际上是在有限字段 GF(2)=Z/2Z 上执行计算而不是普通的实数空间 R^n 中进行处理. 因此标准算法比如 Gaussian elimination 需要做适当调整以便适应这种特殊的算术环境. #### 使用高斯消去法解决问题 一旦建立了这样的数学框架之后,就可以采用经典的 Gauss-Jordan Elimination 方法逐步简化增广矩阵直到得到唯一可行解或者是证明无解存在为止。特别注意当面对大规模实例时效率问题变得至关重要因此也可能考虑其他更高效的替代策略例如 Bitmasking Techniques 结合快速傅立叶变换 FFT 加速乘法步骤等等优化手段提升性能表现水平. 以下是用 Python 编写的简单例子展示如何运用 NumPy 库完成基本功能演示: ```python import numpy as np def create_matrix(m,n): """Create coefficient matrix for lights out game.""" size=m*n mat=np.zeros((size,size)) # Fill diagonal elements and neighbors based on grid structure. for r in range(m): for c in range(n): idx=r*n+c # Current cell itself always toggles. mat[idx,idx]=1 # Toggle top neighbor if exists. if r>0: mat[(r-1)*n+c,idx]=mat[idx,(r-1)*n+c]=1 # Bottom neighbor similarly handled... ... return mat.astype(int) # Example usage creating small test case setup. if __name__=="__main__": M,N=(5,6) initial_state=[[int(c)for c in line.strip().split()]for _in range(M)] target_vector=sum(initial_state,[]) coeff_mat=create_matrix(M,N) augmented=np.hstack([coeff_mat,np.array(target_vector).reshape(-1,1)]) rank_before_elim=np.linalg.matrix_rank(coeff_mat) reduced_form,rref_rows,_=gauss_jordan(augmented) solution_exists=len(rref_rows)==len(set(map(tuple,reduced_form[:,-1]))) print("Solution Exists:",solution_exists) ``` 以上脚本片段仅作为概念验证用途并未完全覆盖边界情形检测等功能完善需求实际部署前还需进一步测试改进确保鲁棒性和兼容性良好。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值