题目地址:http://poj.org/problem?id=1729
本来想用string保存路程 后来发现太慢了
优先队列要以一条路中最近的距离排序
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cmath>
#include<cstring>
using namespace std;
const int maxn=30+5;
const double INF=999999999;
char G[maxn][maxn];
int vis[maxn][maxn][maxn][maxn];
int n;
struct Point{int x,y;Point(int x=0,int y=0):x(x),y(y){}bool operator == (const Point& p){return x==p.x&&y==p.y;}bool operator != (const Point& p){return !(*this==p);}
};
int inline Dist(Point a,Point b){return (a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y);
}
struct Node{Point Jack,Jill; int dist,pre,id; //dist 保存此路中相聚最近的距离 int d1,d2;Node(Point a=Point(0,0),Point b=Point(0,0),int pre=-1,int id=0,int p1='*',int p2='*',int dist=INF):id(id),Jack(a),Jill(b),d1(p1),d2(p2),pre(pre),dist(dist){}bool operator < (const Node& n) const {return dist<n.dist;}
}node[1000000+10];
const int dx[4]={-1,0,1,0};
const int dy[4]={0,-1,0,1};
const char d[5]="NWSE";
Point move(Point p,int i) {return Point(p.x+dx[i],p.y+dy[i]);
}
bool inside(Point p){return p.x>=1&&p.x<=n&&p.y>=1&&p.y<=n;
}int Min=INF;
int cnt;
void BFS(Point s1,Point s2,Point t1,Point t2)
{memset(vis,-1,sizeof(vis));priority_queue<Node> PQ;Node s(s1,s2,-1,0,'*','*',Dist(s1,s2));PQ.push(s); cnt=0; node[cnt++]=s;vis[s1.x][s1.y][s2.x][s2.y]=Dist(s1,s2);while(!PQ.empty()){Node u=PQ.top(); PQ.pop();if(u.Jack==t1&&u.Jill==t2){printf("%.2f\n",sqrt(u.dist));string str1,str2;Node p=u;while(p.pre!=-1){if(p.d1!='*') str1+=p.d1;if(p.d2!='*') str2+=p.d2;p=node[p.pre];}reverse(str1.begin(),str1.end());reverse(str2.begin(),str2.end());cout<<str1<<endl;cout<<str2<<endl;return;}for(int i=0;i<4;i++){Point ns1=move(u.Jack,i); int d1=d[i];if(u.Jack==t1) ns1=u.Jack,d1='*';if(!inside(ns1)||G[ns1.x][ns1.y]=='#'||G[ns1.x][ns1.y]=='*') continue;for(int j=0;j<4;j++){Point ns2=move(u.Jill,j); int d2=d[j];if(u.Jill==t2) ns2=u.Jill,d2='*';if(!inside(ns2)||G[ns2.x][ns2.y]=='*'||G[ns2.x][ns2.y]=='$') continue;int dis=min(u.dist,Dist(ns1,ns2));Node v(ns1,ns2,u.id,cnt,d1,d2,dis);int& vt=vis[ns1.x][ns1.y][ns2.x][ns2.y];if(vt==-1||vt<dis) {vt=dis;PQ.push(v); node[cnt++]=v;}}}}
}
int main()
{while(cin>>n&&n){Point s1,s2,t1,t2;for(int i=1;i<=n;i++)for(int j=1;j<=n;j++){cin>>G[i][j];if(G[i][j]=='H') s1=Point(i,j),G[i][j]='$';else if(G[i][j]=='h') s2=Point(i,j),G[i][j]='#';else if(G[i][j]=='S') t1=Point(i,j),G[i][j]='$';else if(G[i][j]=='s') t2=Point(i,j),G[i][j]='#';}BFS(s1,s2,t1,t2);}return 0;}