Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdio>
- #include <queue>
- #include <vector>
- #include <cstring>
- #include <algorithm>
- using namespace std;
- #define forn(i,n) for(int i=0;i<(int)(n);i++)
- #define DBG(x) //cerr << #x << " = " << x << endl;
- #define RAYA //cerr << endl << "------------------------------------" << endl;
- int w,h,g,e,c,n;
- char maze[30*30];
- pair<int, pair<int,int> > edges[31*31*31*31];
- pair<int, pair<int,int> > holes[30*30];
- bool visited[30*30];
- int dx[] = {-1,0,0,1};
- int dy[] = {0,-1,1,0};
- #define copy(p,q) {(p).first = (q).first; (p).second.first = (q).second.first; (p).second.second = (q).second.second; }
- #define set(p,a,b,c) {(p).first = a; (p).second.first = b; (p).second.second = c; }
- int dist[31*31];
- const int INF = 0x7f7f7f7f, NINF = 0x8f7f7f7f;
- int bfs(int s, int e){
- memset(visited, 0, sizeof(visited));
- queue< pair<int,int> > q;
- q.push(make_pair(0,s));
- visited[s] = true;
- while(!q.empty()){
- int t = q.front().first, p = q.front().second;
- q.pop();
- if(p == e) return t;
- forn(i,4){
- int nr = (p/w+dx[i]), nc = (p%w+dy[i]);
- int npos = nr*w+nc;
- if(nr >= 0 && nc >= 0 && nr < h && nc < w && maze[npos] == '.' && !visited[npos]){
- visited[npos] = true;
- q.push(make_pair(t+1,npos));
- }
- }
- }
- return INF;
- }
- bool bford(){
- forn(i,w*h) dist[i] = INF;
- dist[w*(h-1)] = 0;
- forn(i, n)
- forn(j, c){
- int source = edges[j].first,
- dest = edges[j].second.second,
- weight = edges[j].second.first;
- dist[dest] = min(dist[source]+weight,dist[dest]);
- }
- forn(j, c){
- int source = edges[j].first,
- dest = edges[j].second.second,
- weight = edges[j].second.first;
- if(dist[dest] > dist[source]+weight)
- return true;
- }
- return false;
- }
- int main(){
- #ifndef ONLINE_JUDGE
- freopen("GRAVEYRD.in","r",stdin);
- #endif
- while(scanf("%d %d\n",&w,&h) && w != 0){
- scanf("%d\n",&g);
- forn(i,w*h) maze[i] = '.';
- forn(i,g){
- int r,c; scanf("%d %d\n",&c,&r);
- r = h-r-1;
- maze[r*w+c] = '#';
- }
- scanf("%d\n", &e);
- forn(i,e){
- int sr,sc,er,ec,t;
- scanf("%d %d %d %d %d",&sc,&sr,&ec,&er,&t);
- sr = h-sr-1;
- er = h-er-1;
- set(holes[i],sr*w+sc,t,er*w+ec);
- }
- n = e+2;
- int start = w*(h-1);
- int end = w-1;
- c = 0;
- set(edges[c],start,bfs(start,end),end);
- c++;
- forn(i,e){
- copy(edges[c],holes[i]);
- c++;
- set(edges[c],start,bfs(start,holes[i].first),holes[i].first);
- c++;
- set(edges[c],holes[i].second.second, bfs(holes[i].second.second, end),end);
- c++;
- }
- forn(i, e)
- forn(j, e){
- set(edges[c],holes[i].second.second,bfs(holes[i].second.second,holes[j].first),holes[j].first);
- c++;
- }
- bool res = bford();
- if(res){
- printf("Never\n");
- }else{
- if(dist[w-1] < INF) printf("%d\n",dist[w-1]);
- else printf("Impossible\n");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment