bfs+状态压缩。水题。
一開始我非常挫的用了 vis[21][21][2][2][2][2][2][2][2][2][2][2]; G++,300+ms;
然后后来想到能够用二进制啊。
笨。就改成了 vis[21][21][1024] G++,78ms;
#include<cstdio>
#include<cstring>
#include<string>
#include<queue>
#include<algorithm>
#include<map>
#include<stack>
#include<iostream>
#include<list>
#include<set>
#include<bitset>
#include<vector>
#include<cmath>
#define INF 0x7fffffff
#define eps 1e-8
#define LL long long
#define PI 3.141592654
#define CLR(a,b) memset(a,b,sizeof(a))
#define FOR(i,a,n) for(int i= a;i< n ;i++)
#define FOR0(i,a,b) for(int i=a;i>=b;i--)
#define pb push_back
#define mp make_pair
#define debug puts("==fuck==")
#define acfun std::ios::sync_with_stdio(false)
#define SIZE 20+1
using namespace std;
int xx[]={0,0,-1,1};
int yy[]={-1,1,0,0};
int num[]={512,256,128,64,32,16,8,4,2,1};
struct lx
{
int x,y,t;
int key;
void init(int xx,int yy,int tt,int kk)
{
x=xx,y=yy,t=tt,key=kk;
}
};
lx start,thend;
int n,m,tt;
int g[SIZE][SIZE];
bool cheack(int s,int key)
{
bool unlock[10];
FOR(i,0,10)
{
if(key>=num[i])
{
unlock[i]=1;
key-=num[i];
}
else
unlock[i]=0;
}
if(unlock[s])return 1;
else return 0;
}
void bfs()
{
bool vis[SIZE][SIZE][1024];
CLR(vis,0);
vis[start.x][start.y][start.key]=1;
queue<lx>q;
q.push(start);
while(!q.empty())
{
lx tmp=q.front();
q.pop();
if(tmp.x==thend.x&&tmp.y==thend.y&&tmp.t<thend.t)
{
printf("%d\n",tmp.t);
return;
}
if(tmp.t>=thend.t)continue;
//printf("%d %d %d %d\n",tmp.x,tmp.y,tmp.t,tmp.key);
//system("pause");
FOR(k,0,4)
{
int x=tmp.x+xx[k];
int y=tmp.y+yy[k];
int key=tmp.key;
if(x<0||y<0||x>=n||y>=m||g[x][y]=='*')continue;
if(g[x][y]>='a'&&g[x][y]<='z')
{
if(!cheack(g[x][y]-'a',key))
key+=num[ g[x][y]-'a' ];
}
else if(g[x][y]>='A'&&g[x][y]<='Z')
{
if(!cheack(g[x][y]-'A',key))continue;
}
if(vis[x][y][key])continue;
lx now;
now.init(x,y,tmp.t+1,key);
vis[x][y][key]=1;
q.push(now);
}
}
puts("-1");
}
int main()
{
while(~scanf("%d%d%d",&n,&m,&tt))
{
char str[SIZE];
FOR(i,0,n)
{
scanf("%s",str);
FOR(j,0,m)
{
g[i][j]=str[j];
if(str[j]=='@')start.init(i,j,0,0);
else if(str[j]=='^')thend.init(i,j,tt,0);
}
}
bfs();
}
return 0;
}