首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

一个矩阵的有关问题

2012-04-05 
一个矩阵的问题Each cell of an N x N grid is either a 0 or a 1. You are given two such N x N grids,

一个矩阵的问题
Each cell of an N x N grid is either a 0 or a 1. You are given two such N x N grids, the initial grid and the final grid. There is a button against each row and each column of the initial N x N grid. Pressing a row-button toggles the values of all the cells in that row, and pressing a column-button toggles the values of all the cells in that column. You are required to find the minimum number of button presses required to transform the grid from the initial configuration to the final configuration, and the buttons that must be pressed in order to make this transformation.



[解决办法]
假设这两个矩阵分别为(a_ij) (b_ij) i, j =1,...,N
首先很容易看出任两个反转的动作都是可以交换的,也就是说确定了反转的策略,反转行和列的顺序是无关的
于是可以定义x_1, ..., x_N,y_1,..., y_N
其中x_i表示第i行反转的次数, y_j表示第j列反转的次数
要使次数最少,容易看书x_i, y_j都只能取0或1 (2的效果跟0一样)
比较a_11 和b_11 两个数,分为两种情况:
1. 相同 则x_1=0, y_1=0 or x_1=1, y_1=1

2. 不同 则x_1=0, y_1=1 or x_1=1, y_1=0

对每种情况,分别产生2个策略,并且一旦确定了x_1和y_1的值,根据两个矩阵第一行和第一列的比较,可以立即确定所有的x,y值,这样一个策略就形成了
然后检查这个策略能不能成功:若x_i+x_j=1,a_ij反转;若x_i+x_j=0或2,a_ij不动
如果跟b_ij不相等,这个策略就不行,放弃

简而言之,根据a_11 和b_11的情况,可以产生2个策略,如果2个策略都不成功,那么矩阵a不能变成b
时间复杂度为O(n^2),而且这样的策略需要最少的步数
[解决办法]
可以先根据01的奇偶,做一个快速的无解判断。
另外似乎不存在一行或一列被来回翻转多次的情况,因此两个分支后面,几乎都可以靠贪心一条道走到黑。
不会再有更多的分支了。

[解决办法]
这是二阶域上一个含2n个变量,n^2条方程的线性方程组(而且是稀疏矩阵)。
直接求解线性方程组就可以了。通常应该无解

热点排行