题目大意:
4*4矩阵,矩阵上每个元素都有两种状态开和关,给定初始状态,和状态转移求从初始状态到目标状态:所有元素都是开状态,的最小步骤数以及步骤.
这题也没多想,位压缩+bfs+路径回溯.
状态数最多2^16个
层数最少:bfs
求步骤:只需Mark每个状态的父状态,回溯一遍即可.
附代码:
#include <iostream>
#include <queue>
#include <stack>
#include <cmath>
#include <stdio.h>
using namespace std;
//状态转移
const int method[]={0xf888,0xf444,0xf222,0xf111,
0x8f88,0x4f44,0x2f22,0x1f11,
0x88f8,0x44f4,0x22f2,0x11f1,
0x888f,0x444f,0x222f,0x111f};
const int FIN = 0;
const int MAX = 65536;
struct Path
{
int nStep; //跳转到该状态所需步数。
int nFatherId; //父结点id
int nMethod; //当前节点是父节点的第几个孩子
};
Path stPath[MAX];
std::stack<int> Stack;
int InitData()
{
int i ;
for (i = 0 ;i < MAX ; i ++)
{
stPath[i].nFatherId = -1;
stPath[i].nMethod = -1;
stPath[i].nStep = - 1;
}
return 0;
}
int input()
{
int i ,j;
char ch;
int nInitState = 0;
for(i = 0 ;i < 4; i ++)
{
for (j = 0 ;j < 4; j ++)
{
ch = getchar();
if('+' == ch)
{
nInitState += (int)(pow(2.0,1.0*(15 - i* 4 - j)));
}
}
getchar();
}
return nInitState;
}
int bfs(int nInitState)
{
std::queue<int> Queue;
//初始状态入队列
Queue.push(nInitState);
stPath[nInitState].nStep = 0;
while(!Queue.empty())
{
int nFrontStatue = Queue.front();
Queue.pop();
int i ;
for (i = 0 ;i < 16 ;i ++)
{
int nCurStatue = nFrontStatue ^ method[i];
if (stPath[nCurStatue].nStep == -1)
{
Queue.push(nCurStatue);
stPath[nCurStatue].nStep = stPath[nFrontStatue].nStep + 1;
stPath[nCurStatue].nMethod = i;
stPath[nCurStatue].nFatherId = nFrontStatue;
}
if (nCurStatue == FIN)
{
return nCurStatue;
}
}
}
return -1;
}
int findPath(int nEnd)
{
int i;
i = nEnd;
Stack.push(stPath[i].nMethod);
while(1)
{
i = stPath[i].nFatherId;
if (stPath[i].nFatherId == -1)
{
break;
}
Stack.push(stPath[i].nMethod);
}
return 0;
}
int main()
{
int nInitState = input();
InitData();
int nRes = bfs(nInitState);
findPath(nRes);
cout<<stPath[nRes].nStep<<endl;
while (!Stack.empty())
{
int nPos = Stack.top();
Stack.pop();
cout<<nPos / 4 + 1<<" ";
cout<<nPos % 4 + 1<<endl;
}
return 0;
};
看到网上有人用递推秒杀此题,感觉自己弱爆了.....
1.一个元素翻转奇数次状态不变,翻转偶数次状态改变
由1容易推到出2
2:要想把第Sij翻转,同时保持第i行和第j列其他元素状态不变,sij本身翻转两次,第i和第j列的其他元素翻转一次.
由把所有状态为关的元素都做一次2操作,记录那些元素状态变化过,变化过的元素个数即最小步骤数.
由以上分析得出,各个元素的步骤顺序其实是无所谓的.把变化的过元素按任意顺序输出即步骤.
附代码:
#include <iostream>
#include <queue>
bool mark[4][4];
struct Pos
{
int x;
int y;
};
std::queue<Pos> Ans;
int input()
{
memset(mark,0,sizeof(mark));
int i ,j,k;
char ch;
for (i = 0 ;i < 4 ; ++ i)
{
for (j = 0 ;j < 4 ; ++j)
{
ch = getchar();
if ('+' == ch)
{
mark[i][j] = !mark[i][j];
for(k = 0 ; k < 4 ; k ++)
{
mark[i][k] = !mark[i][k];
mark[k][j] = ! mark[k][j];
}
}
}
getchar();
}
return 0;
}
int main()
{
int nStep = 0;
int i,j;
input();
for ( i = 0 ; i < 4; ++i)
{
for (j = 0 ; j < 4 ; ++j)
{
if (mark[i][j])
{
nStep ++;
Pos pos;
pos.x = i + 1;
pos.y = j + 1;
Ans.push(pos);
}
}
}
std::cout <<nStep<<std::endl;
while (!Ans.empty())
{
Pos pos = Ans.front();
Ans.pop();
std::cout<<pos.x<<" "<<pos.y<<std::endl;
}
return 0;
};