您的位置:首页 > 其它

[挑战程序设计竞赛] AOJ 0558 - Cheese

2014-11-27 20:18 351 查看
在H * W的地图上有N个奶酪工厂,每个工厂分别生产硬度为1-N的奶酪。有一只老鼠准备从出发点吃遍每一个工厂的奶酪。老鼠有一个体力值,初始时为1,每吃一个工厂的奶酪体力值增加1(每个工厂只能吃一次),且老鼠只能吃硬度不大于当前体力值的奶酪。

老鼠从当前格到上下左右相邻的无障碍物的格需要时间1单位,有障碍物的格不能走。走到工厂上时即可吃到该工厂的奶酪,吃奶酪时间不计。问吃遍所有奶酪最少用时。
输入:三个整数H(1 <= H <= 1000)、W(1 <= W <=1000)、N(1 <= N <= 9),之后H行W列为地图, “.“为空地, ”X“为障碍物,”S“为老鼠洞, 1-N代表硬度为1-N的奶酪的工厂。

输出:吃完所有奶酪的最少时间。

题目保证有解。。

根据题意直接先BFS奶酪硬度小的。然后把这个奶酪工厂所在的位置作为起点,继续BFS即可。。

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <algorithm>
#include <iostream>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <assert.h>
#include <time.h>
typedef long long LL;
const int INF = 500000001;
const double EPS = 1e-9;
const double PI = acos(-1.0);
using namespace std;
int H, W, N, ans, sum;
int dir[4][2] = {-1,0, 1,0, 0,-1, 0,1};
char ch[1005][1005], temp[1005][1005];
int len[1005][1005];
struct p
{
int x, y;
}fir, en;
queue<p> qq;
bool bfs()
{
while(!qq.empty())
{
en = qq.front();
qq.pop();
for(int i = 0; i < 4; i++)
{
fir.x = dir[i][0] + en.x;
fir.y = dir[i][1] + en.y;
if(temp[fir.x][fir.y] != 'X')
{
len[fir.x][fir.y] = len[en.x][en.y] + 1;
if(temp[fir.x][fir.y] == '0' + sum)
{
ans += len[fir.x][fir.y];
++sum;
while(!qq.empty())
{
qq.pop();
}
return true;
}
temp[fir.x][fir.y] = 'X';
qq.push(fir);
}
}
}
return false;
}
int main()
{
//freopen("test0.in", "r", stdin);
//freopen("test0.out", "w", stdout);
//srand(time(NULL));
while(~scanf("%d %d %d", &H, &W, &N))
{
sum = 1;
ans = 0;
getchar();
memset(ch, 'X', sizeof(ch));
for(int i = 1; i <= H; i++)
{
for(int j = 1; j <= W; j++)
{
ch[i][j] = getchar();
if(ch[i][j] == 'S')
{
fir.x = i;
fir.y = j;
}
}
getchar();
}
memcpy(temp, ch, sizeof(ch));
qq.push(fir);
len[fir.x][fir.y] = 0;
temp[fir.x][fir.y] = 'X';
while(bfs())
{
memcpy(temp, ch, sizeof(ch));
len[fir.x][fir.y] = 0;
temp[fir.x][fir.y] = 'X';
qq.push(fir);
}
printf("%d\n", ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息