POJ 3669 Meteor Shower

#include<iostream>
#include<stdio.h>
#include<queue>
#include<utility>
#include<memory.h>
using namespace std;

#define INF 1e9+7 

typedef struct loca
{
	int x, y, t;
	loca(int a, int b, int c){x=a,y=b,t=c;}
}loca;

int n, ans = INF;
int map[500][500];
int dir[4][2] = {1,0,-1,0,0,1,0,-1};
queue<loca> que;


int bfs()
{
	que.push(loca(0, 0, 0));
	while(!que.empty())
	{
		loca p = que.front(); que.pop();
		int x = p.x, y = p.y, t = p.t;
		if(map[x][y] == INF) return t;
		
		for(int i = 0; i < 4; i++)
		{
			int nx = x+dir[i][0], ny = y+dir[i][1];
			if(nx >= 0 && ny >= 0 && t+1 < map[nx][ny])
            { 
                if(map[nx][ny] != INF) map[nx][ny] = t+1;  // **防止回退 (if一定要加)
				que.push(loca(nx, ny, t+1));
            }
		}
	}
	return -1; 
}

int main()
{
	cin >> n;
	for(int i = 0; i < 500; i++) for(int j = 0; j < 500; j++) map[i][j] = INF;
	for(int i = 0; i < n; i++) 
	{
		int a, b, t;
		scanf("%d %d %d", &a, &b, &t);
		map[a][b] = min(map[a][b], t);
		if(a-1 >= 0) map[a-1][b] = min(map[a-1][b], t); //重叠区域的值要选择t值较小的
		map[a+1][b] = min(map[a+1][b], t);
		if(b-1 >= 0) map[a][b-1] = min(map[a][b-1], t);
        map[a][b+1] = min(map[a][b+1], t);
	}
	cout << bfs();
    system("pause");
	return 0;
}
上一篇:Sentou


下一篇:SAP成本还原的一些知识