POJ NO.3669 Meteor Shower(經典BPS,,,)

問題描述:

給你一個整數M表示流行的個數,然後給你M組數據每組包含3個整數,分別表示座標和降落的時間。

題目鏈接:點擊打開鏈接

思路:

先把時間都標記好,在跑一遍BFS即可。

注意:走過的點不能再走!!!還要注意時間,這種解法很費時所以將輸入輸出流換成了scanf,,,,,

代碼:

#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#define INF 0x3f3f3f3f

using namespace std;

struct P
{
    int x, y, z;
};

const int MAX = 302;
int field[MAX][MAX], foot[MAX][MAX];//foot用來判斷是否該點是否走過
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};

int BFS();

int main()
{
    int t, arr[MAX][MAX];
    while(~scanf("%d", &t))
    {
        //把所有點都給賦值爲INF
        for(int i = 0; i < 302; i++)
            for(int j = 0; j < 302; j++) field[i][j] = INF;
        //給數組foot全部賦值爲0,表示所有的點都沒走過
        memset(foot, 0, sizeof(foot));
        //給所有的點標記上時間(有流星來的時間)
        while(t--)
        {
            int x, y, z;
            scanf("%d%d%d", &x, &y, &z);
            if(field[x][y] > z)
                field[x][y] = z;
            for(int i = 0; i < 4; i++)
            {
                int nx = x + dx[i], ny = y + dy[i];
                if(nx >= 0 && nx <= 302 && ny >= 0 &&
                        ny <= 302 && field[nx][ny] > z)
                    field[nx][ny] = z;
            }
        }
        //跑一遍BFS即可
        int res = BFS();
        cout << res << endl;
    }
}

int BFS()
{
    queue<P> que;
    que.push((P)
    {
        0, 0, 0
    });
    while(que.size())//直到隊列長度爲0
    {
        P p = que.front();
        que.pop();
        if(field[p.x][p.y] == INF) return p.z;
        if(foot[p.x][p.y]) continue;//走過不能再走了(排除走過的點重新走的可能)
        foot[p.x][p.y] = 1;//標記該點已經走過
        for(int i = 0; i < 4; i++)
        {
            P n;
            n.x = p.x + dx[i];
            n.y = p.y + dy[i];
            n.z = p.z + 1;
            if(0 <= n.x && n.x < 302 && 0 <= n.y && n.y < 302 &&
                    n.z < field[n.x][n.y] && foot[n.x][n.y] == 0)
            {
                que.push(n);
            }
        }
    }
    return -1;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章