[挑战程序设计竞赛] POJ 3699 - Meteor Shower

来源:互联网 发布:上海师范大学网络教育 编辑:程序博客网 时间:2024/06/05 20:04

题意:

给定M个坐标上会在T秒时掉落一颗陨石,人最初在坐标(0,0),人在当前坐标每走到四周的格子需要花费时间1秒。

问这个人至少需要多少秒才能到达安全地带?(人可以在第一象限随便走~)


BFS的过程中判断人是否被陨石碰到,碰到的地方就不能继续往下搜了,还有如果在坐标(0,0)第0秒有陨石掉落,人直接就被砸到了。。要输出-1。

#include <stdio.h>#include <string.h>#include <queue>using namespace std;int graph[500][500], len[500][500];int dir[5][2] = {-1,0, 1,0, 0,1, 0,-1, 0,0};struct p{    int x, y;}st, en;queue<p> qq;bool check(int x, int y){    for(int i = 0; i < 5; i++)    {        if(graph[x+dir[i][0]][y+dir[i][1]] >= 0)        {            return false;        }    }    return true;}int ck(int x, int y){    int ans = 20000;    for(int i = 0; i < 5; i++)    {        if(graph[x+dir[i][0]][y+dir[i][1]] >= 0)        {            ans = min(ans, graph[x+dir[i][0]][y+dir[i][1]]);        }    }    return ans;}int bfs(){    while(!qq.empty())    {        en = qq.front();        qq.pop();        for(int i = 0; i < 4; i++)        {            st.x = en.x + dir[i][0];            st.y = en.y + dir[i][1];            if(graph[st.x][st.y] != -1 && len[st.x][st.y] == -1)            {                len[st.x][st.y] = len[en.x][en.y] + 1;                if(check(st.x, st.y))                {                    while(!qq.empty())                    {                        qq.pop();                    }                    //printf("[%d %d]\n", st.x, st.y);                    return len[st.x][st.y];                }                else                {                    if(len[st.x][st.y] < ck(st.x, st.y))                    {                        qq.push(st);                    }                }            }        }    }    return -1;}void init(){    for(int i = 0; i < 500; i++)    {        graph[0][i] = -1;        graph[i][0] = -1;    }    for(int i = 1; i < 500; i++)    {        for(int j = 1; j < 500; j++)        {            graph[i][j] = -2;        }    }}int main(){    int M, x, y, T;    while(~scanf("%d", &M))    {        memset(len, -1, sizeof(len));        init();        for(int i = 0; i < M; i++)        {            scanf("%d %d %d", &x, &y, &T);            graph[x+1][y+1] = T;        }        if(check(1,1))        {            printf("0\n");            continue;        }        len[1][1] = 0;        st.x = st.y = 1;        qq.push(st);        printf("%d\n", bfs());    }    return 0;}

0 0
原创粉丝点击