和暑假一道多校脸萌的题一样
题意:就是有N个奶酪工厂。每个工厂的奶酪对应1,2,3-N,每次一块奶酪老鼠的体力会加1,他只能吃比小于等于自己体力值的奶酪。初始体力为1。每个工厂只能吃一次。求吃完所有工厂需要最小的步数。
思路:只能按照顺序去吃,所以是多次bfs 即可。
代码如下:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<vector>
#include<string>
#include<queue>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
const int MAX = 1010;
char str[MAX][MAX];
bool used[MAX][MAX];
const int xx[] = {1,0,-1,0};
const int yy[] = {0,-1,0,1};
int H,W,N;
class Point{
public:
int x,y;
int t;
Point(int xx=0,int yy = 0,int tt=0){
x = xx;
y = yy;
t = tt;
}
};
Point now;
bool Check(Point A){
if(A.x < 0 || A.y < 0 || A.x >= H || A.y >= W)//注意范围
return false;
return true;
}
int bfs(Point B,char factory){
queue<Point> q;
while(!q.empty()) q.pop();
q.push(B);
while(!q.empty()){
Point v = q.front();q.pop();
for(int i=0;i<4;++i){
int tx = v.x + xx[i];
int ty = v.y + yy[i];
int tt = v.t + 1;
if(!Check(Point(tx,ty,tt)) || str[tx][ty] == 'X')
continue;
if(str[tx][ty] == factory){
now = Point(tx,ty,0);//步数要再次初始为0
return tt;
}
if(!used[tx][ty]){
used[tx][ty] = true;
q.push(Point(tx,ty,tt));
}
}
}
return 0;
}
int solve(){
int res = 0;
for(int i=1;i<=N;++i){
memset(used,false,sizeof(used));
res += bfs(now,i+'0');
}
return res;
}
int main(void){
scanf("%d%d%d",&H,&W,&N);
for(int i=0;i<H;++i){
scanf("%s",str[i]);
for(int j=0;j<W;++j){
if(str[i][j] == 'S'){
now = Point(i,j,0);
}
}
}
printf("%d\n",solve());
return 0;
}