Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- ifstream fin("walle.in");
- ofstream fout("walle.out");
- struct ceva
- {
- int x,y;
- } p,p1,p2,port[501*501],ex,wally;
- queue <ceva> q;
- int dx[]= {0, -1, 0, 1, 0};
- int dy[]= {0, 0, 1, 0, -1};
- int lee[510][510],a[510][510],fol[510][510],n,m,i,j,portalparc,t,nr,trans,k,minim=999999999;
- char mat[510][510];
- int in(ceva a)
- {
- return (a.x>=1 && a.x<=n && a.y>=1 && a.y<=m);
- }
- int cmp(ceva a,ceva b)
- {
- return lee[a.x][a.y]>lee[b.x][b.y];
- }
- int main()
- {
- fin>>n>>m>>t;
- for(i=1; i<=n; i++)
- for(j=1; j<=m; j++)
- {
- lee[i][j]=999999999;
- a[i][j]=999999999;
- fin>>mat[i][j];
- if(mat[i][j]=='P')
- port[++nr].x=i, port[nr].y=j;
- if(mat[i][j]=='W')
- wally.x=i, wally.y=j, lee[i][j]=0;
- if(mat[i][j]=='E')
- ex.x=i, ex.y=j;
- }
- q.push(ex);
- lee[ex.x][ex.y]=0;
- while(!q.empty())
- {
- p1=q.front();
- q.pop();
- if(mat[p1.x][p1.y]=='+')
- trans=t+1;
- else trans=1;
- for(i=1; i<=4; i++)
- {
- p2.x=p1.x+dx[i];
- p2.y=p1.y+dy[i];
- if(in(p2) && lee[p2.x][p2.y] > lee[p1.x][p1.y]+trans && mat[p2.x][p2.y]!='#')
- {
- lee[p2.x][p2.y]=lee[p1.x][p1.y]+trans;
- q.push(p2);
- }
- }
- }
- sort(port+1,port+nr+1,cmp);
- a[wally.x][wally.y]=0;
- q.push({wally.x,wally.y});
- while(!q.empty())
- {
- minim=min(minim,a[ex.x][ex.y]);
- p1=q.front();
- q.pop();
- if(mat[p1.x][p1.y]=='+')
- trans=t+1;
- else trans=1;
- for(i=1; i<=4; i++)
- {
- p2.x=p1.x+dx[i];
- p2.y=p1.y+dy[i];
- if(mat[p1.x][p1.y]==mat[p2.x][p2.y] && mat[p1.x][p1.y]=='P')
- continue;
- if(in(p2) && mat[p2.x][p2.y]!='#' && a[p2.x][p2.y] > a[p1.x][p1.y] + trans)
- {
- a[p2.x][p2.y]=a[p1.x][p1.y]+trans;
- if(mat[p2.x][p2.y]!='P')
- q.push(p2);
- else
- {
- if(port[1].x==p2.x && port[1].y==p2.y)
- {
- a[port[2].x][port[2].y]=a[p2.x][p2.y];
- fol[port[2].x][port[2].y]++;
- q.push(port[2]);
- }
- else
- {
- a[port[1].x][port[1].y]=a[p2.x][p2.y];
- fol[port[1].x][port[1].y]++;
- q.push(port[1]);
- }
- }
- }
- else if(in(p2) && mat[p2.x][p2.y]=='P' && fol[p2.x][p2.y]<=nr)
- {
- if(port[1].x==p2.x && port[1].y==p2.y && fol[port[2].x][port[2].y]<=nr)
- {
- a[port[2].x][port[2].y]=a[p1.x][p1.y]+trans;
- fol[port[2].x][port[2].y]++;
- q.push(port[2]);
- }
- else if(fol[port[1].x][port[1].y]<=nr)
- {
- a[port[1].x][port[1].y]=a[p1.x][p1.y]+trans;
- fol[port[1].x][port[1].y]++;
- q.push(port[1]);
- }
- }
- }
- }
- if(minim==999999999)
- fout<<-1;
- else fout<<minim;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement