此题我是写了个BFS过的,用的队列是STL的queue,960ms过的。。
用2进制来压缩状态,然后列出20种操作数op[i]。
于是在i处的操作就等同于对now=now^op[i],和Flip Game的处理方法一样。
但是他们写的BFS会TLE就不知道为什么了。。还有用DFS过的= =
后来,得知了一个枚举加贪心的方法,但是没法证明是最优的,得去查查资料。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <cmath>
using namespace std;
struct T
{
int now;
int step;
};
queue<T> q;
bool v[4194304];
int op[20];
int main()
{
int a[30],i,j;
T s,ts,tts;
s.now=0;
s.step=0;
for (i=0; i<20; i++)
{
scanf("%d",a+i);
if (a[i] == 1)
{
s.now+=1<<i;
}
if (i == 19)
{
op[i]=3<<18;
}
else if (i == 0)
{
op[i]=3;
}
else
{
op[i]=7<<(i-1);
}
}
while (!q.empty())
q.pop();
q.push(s);
memset(v,false,sizeof(v));
v[s.now]=true;
while (!q.empty())
{
ts=q.front();
q.pop();
if (ts.now == 0)
{
printf("%d\n",ts.step);
return 0;
}
for (i=0; i<20; i++)
{
tts.now=ts.now^op[i];
tts.step=ts.step+1;
if (v[tts.now] == false)
{
v[tts.now]=true;
q.push(tts);
}
}
}
}