题目链接:http://acm.fzu.edu.cn/problem.php?pid=2150
题意:在任意两处点火,求最短时间烧光所有草堆。
规模:1 <= T <=100, 1 <= n <=10, 1 <= m <=10
类型:暴力+双搜
分析:题目很好理解,枚举两个起点进行双搜就好。但以前没有敲过双搜,中间出了不少状况,wa了很多发,主要问题是在“如何使两个queue完成当前时间下的搜索”。
时间复杂度&&优化:
代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<queue>
#include<stack>
#include<math.h>
#include<vector>
#include<algorithm>
#include<iostream>
using namespace std;
const int MAX_N = 100005;
const int MAX_M = 5005;
const int inf = 1000000007;
const int mod = 1000000007;
int n,m;
int a[15][15];
int b[15][15];
struct point{
int x,y;
int step;
};
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
bool judge(int x,int y){
if(x>=0&&x<n&&y>=0&&y<m&&b[x][y]==1){
b[x][y]=0;
//cout<<"!"<<endl;
return true;
}
return false;
}
int bfs(int ax,int ay,int bx,int by){
int res=0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
b[i][j]=a[i][j];
}
}
b[ax][ay]=0;
b[bx][by]=0;
queue<point>q,p;
while(!q.empty()){q.pop();}
while(!p.empty()){p.pop();}
point st1,st2;
st1.x=ax;st1.y=ay;st1.step=0;
st2.x=bx;st2.y=by;st2.step=0;
q.push(st1);p.push(st2);
int stp=0;
point tmp,tmp2;
while(!q.empty() || !p.empty()){
if(!q.empty()){
int key_step=q.front().step;
while(!q.empty()&&q.front().step==key_step){
tmp=q.front();
//cout<<tmp.x<<" "<<tmp.y<<" "<<tmp.step<<endl;
q.pop();
stp=tmp.step;
res=max(res,stp);
for(int i=0;i<4;i++){
tmp2.x=tmp.x+dx[i];
tmp2.y=tmp.y+dy[i];
tmp2.step=tmp.step+1;
if(judge(tmp2.x,tmp2.y))q.push(tmp2);
}
// if(ax==1&&ay==1&&bx==7&&by==2){
// cout<<stp<<" "<<tmp.x<<" "<<tmp.y<<endl;
// }
}
}
if(!p.empty()){
int key_step=p.front().step;
while(!p.empty()&&p.front().step==key_step){
tmp=p.front();
p.pop();
stp=tmp.step;
res=max(res,stp);
for(int i=0;i<4;i++){
tmp2.x=tmp.x+dx[i];
tmp2.y=tmp.y+dy[i];
tmp2.step=tmp.step+1;
if(judge(tmp2.x,tmp2.y))p.push(tmp2);
}
// if(ax==1&&ay==1&&bx==7&&by==2){
// cout<<stp<<" "<<tmp.x<<" "<<tmp.y<<endl;
// }
}
}
}
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(b[i][j]==1)return -1;
}
}
// //cout<<stp<<" "<<ax<<" "<<ay<<" "<<bx<<" "<<by<<endl;
// if(stp==3)cout<<3<<" "<<ax<<" "<<ay<<" "<<bx<<" "<<by<<endl;
// if(stp==4)cout<<4<<" "<<ax<<" "<<ay<<" "<<bx<<" "<<by<<endl;
return res;
}
int solve(){
int res=inf;
for(int i=0;i<n*m;i++){
if(a[i/m][i%m]==1)
for(int j=i+1;j<n*m;j++){
if(a[j/m][j%m]==1){
// cout<<i<<" "<<j<<endl;
int k=bfs(i/m,i%m,j/m,j%m);
if(k!=-1)res=min(res,k);
}
}
}
if(res==inf)return -1;
else return res;
}
int main()
{
//freopen("test.txt","r",stdin);
int T;char c;
cin>>T;
for(int z=1;z<=T;z++){
memset(a,0,sizeof(a));
cin>>n>>m;
int tot=0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>c;
if(c=='#'){a[i][j]=1;tot++;}
else a[i][j]=0;
}
}
if(tot<=2){printf("Case %d: %d\n",z,0);}
else printf("Case %d: %d\n",z,solve());
}
return 0;
}