优先队列+bfs
AC Code
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 using namespace std; 5 int vis[25][25]; 6 int map[25][25],tmp[25][25]; 7 int k; 8 int x1,y1,x2,y2,r,c; 9 struct 10 { 11 int x,y,val; 12 }a[505]; 13 void down() 14 { 15 int x=a[k].x,y=a[k].y,val=a[k].val,i=1,j=2; 16 k--; 17 while(j<=k){ 18 if(a[j].val>a[j+1].val&&j+1<=k) 19 j++; 20 if(val>a[j].val){ 21 a[i].x=a[j].x; 22 a[i].y=a[j].y; 23 a[i].val=a[j].val; 24 i=j; 25 j=2*i; 26 } 27 else 28 break; 29 } 30 a[i].x=x; 31 a[i].y=y; 32 a[i].val=val; 33 } 34 void up() 35 { 36 int i=k,x=a[k].x,y=a[k].y,val=a[k].val; 37 while(i>1){ 38 if(a[i/2].val>val){ 39 a[i].x=a[i/2].x; 40 a[i].y=a[i/2].y; 41 a[i].val=a[i/2].val; 42 i/=2; 43 } 44 else 45 break; 46 } 47 a[i].x=x; 48 a[i].y=y; 49 a[i].val=val; 50 } 51 void bfs() 52 { 53 if(vis[x2][y2]==1||k==0) 54 return; 55 int x=a[1].x,y=a[1].y,val=a[1].val; 56 if(vis[x-1][y]==0&&x-1>=0){ 57 map[x-1][y]=val+map[x-1][y]; 58 vis[x-1][y]=1; 59 a[++k].x=x-1; 60 a[k].y=y; 61 a[k].val=map[x-1][y]; 62 up(); 63 } 64 if(vis[x+1][y]==0&&x+1<r){ 65 map[x+1][y]=val+map[x+1][y]; 66 vis[x+1][y]=1; 67 a[++k].x=x+1; 68 a[k].y=y; 69 a[k].val=map[x+1][y]; 70 up(); 71 } 72 if(vis[x][y-1]==0&&y-1>=0){ 73 map[x][y-1]=val+map[x][y-1]; 74 vis[x][y-1]=1; 75 a[++k].x=x; 76 a[k].y=y-1; 77 a[k].val=map[x][y-1]; 78 up(); 79 } 80 if(vis[x][y+1]==0&&y+1<c){ 81 map[x][y+1]=val+map[x][y+1]; 82 vis[x][y+1]=1; 83 a[++k].x=x; 84 a[k].y=y+1; 85 a[k].val=map[x][y+1]; 86 up(); 87 } 88 down(); 89 bfs(); 90 } 91 int main() 92 { 93 int cas=1; 94 while(~scanf("%d%d",&r,&c)){ 95 int p,s,t; 96 char op; 97 scanf("%d%d%d",&p,&s,&t); 98 getchar(); 99 memset(vis,0,sizeof(vis)); 100 for(int i=0;i<r;i++){ 101 for(int j=0;j<c;j++){ 102 scanf("%c",&op); 103 if(op=='T') 104 map[i][j]=t; 105 else if(op=='.') 106 map[i][j]=s; 107 else if(op=='#') 108 map[i][j]=p; 109 else{ 110 map[i][j]=-1; 111 vis[i][j]=1; 112 } 113 tmp[i][j]=map[i][j]; 114 } 115 getchar(); 116 } 117 scanf("%d%d%d%d",&x1,&y1,&x2,&y2); 118 printf("Case %d: ",cas++); 119 if(vis[x2][y2]==1){ 120 printf("-1\n"); 121 continue; 122 } 123 vis[x1][y1]=1; 124 k=1; 125 a[1].x=x1; 126 a[1].y=y1; 127 a[1].val=map[x1][y1]; 128 bfs(); 129 if(vis[x2][y2]==0) 130 printf("-1\n"); 131 else 132 printf("%d\n",map[x2][y2]-tmp[x1][y1]); 133 } 134 return 0; 135 }