Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
SPFA 188Ms AC#include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<string> #include<iostream> #include<queue> #include<iomanip> #include<algorithm> using namespace std; const int N=65,M=35; struct edge { int vx,vy,nx,w; }e[N*M*200]; int n,m,map[N][M],d[N][M][2]; int id,head[N][M][2]; struct node { int x,y,d,w; friend bool operator<(const node &a,const node &b) { return a.w>b.w; } }; priority_queue<node>q; void add(int ux,int uy,int vx,int vy,int d) { if(vx<1||vx>n||vy<1||vy>m||map[vx][vy]==-1) return; id++; e[id].vx=vx;e[id].vy=vy;e[id].nx=head[ux][uy][d];head[ux][uy][d]=id; if(map[vx][vy]==10) e[id].w=0; else e[id].w=map[vx][vy]; } void spfa() { int i,j,k,g,x,y,vx,vy; node now,p; memset(d,0x7f,sizeof(d)); while(!q.empty()) q.pop(); for(i=1;i<=n;i++) for(j=1;j<=m;j++) if(map[i][j]==0) { now.x=i;now.y=j;now.w=0; // if(j>1) // { now.d=1; q.push(now); // } // if(j<m) // { now.d=0; q.push(now); // } } while(!q.empty()) { now=q.top(); q.pop();g=now.d; x=now.x;y=now.y; // printf("%d %d %d %d\n",now.x,now.y,now.w,now.d); if(map[x][y]==10) { printf("%d\n",now.w); return; } for(i=head[x][y][g];i!=-1;i=e[i].nx) { vx=e[i].vx;vy=e[i].vy; if(now.w+e[i].w<d[vx][vy][!g]) { p.x=vx;p.y=vy;p.w=now.w+e[i].w; d[vx][vy][!g]=p.w; p.d=!g; q.push(p); } } } printf("-1\n"); } int main() { int i,j,k; char c; while(~scanf("%d%d\n",&m,&n)) { if((n==0)&&(m==0)) break; memset(map,-1,sizeof(map)); memset(head,-1,sizeof(head)); for(i=1;i<=n;i++) { for(j=1;j<=m;j++) { scanf("%c ",&c); if(c=='S') map[i][j]=0; else if(c=='T') map[i][j]=10; else if((c>='1')&&(c<='9')) map[i][j]=c-'0'; } scanf("\n"); } id=0; for(i=1;i<=n;i++) for(j=1;j<=m;j++) { if(map[i][j]==-1||map[i][j]==10) continue; add(i,j,i,j+1,0); add(i,j,i,j+2,0); add(i,j,i,j+3,0); add(i,j,i+2,j+1,0); add(i,j,i+1,j+1,0); add(i,j,i-1,j+1,0); add(i,j,i-2,j+1,0); add(i,j,i-1,j+2,0); add(i,j,i+1,j+2,0); add(i,j,i,j-1,1); add(i,j,i,j-2,1); add(i,j,i,j-3,1); add(i,j,i+2,j-1,1); add(i,j,i+1,j-1,1); add(i,j,i-1,j-1,1); add(i,j,i-2,j-1,1); add(i,j,i-1,j-2,1); add(i,j,i+1,j-2,1); } spfa(); } return 0; } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator