Dijkstra,最短路(蒸汽式压路机,LA 4128)

来源:互联网 发布:java web书籍推荐 2016 编辑:程序博客网 时间:2024/03/28 18:14

任何最短路的本质都是状态的最短路。其中涉及状态的定义以及状态的转移。


代码

#include<bits/stdc++.h>#include<limits.h>#define rep(i,a,b) for(ll i=a;i<=b;i++)using namespace std;typedef long long ll;const ll maxn = 110;const ll inf = LONG_LONG_MAX>>2;ll dr[4]={-1, 0, 1, 0};ll dc[4]={ 0, 1, 0,-1};struct st{    ll r,c;    ll p;    ll t;    ll d;    bool operator < (const st& rhs) const    {        return d>rhs.d;    }};ll G[maxn][maxn][4];ll R,C,r1,c1,r2,c2;ll d[maxn][maxn][4][2];ll done[maxn][maxn][4][2];bool ok(const st& x){    if(x.r<1||x.r>R) return false;    if(x.c<1||x.c>C) return false;    return true;}ll kase;int main(){    while(scanf("%lld %lld %lld %lld %lld %lld",&R,&C,&r1,&c1,&r2,&c2)==6&&R)    {        rep(i,1,R) rep(j,1,C) rep(k,0,3) G[i][j][k]=inf;        rep(i,1,R)        {            rep(j,1,C-1)            {                scanf("%lld",&G[i][j][1]);                G[i][j][1]=G[i][j][1]?G[i][j][1]:inf;                G[i][j+1][3]=G[i][j][1];            }            if(i<R) rep(j,1,C)            {                scanf("%lld",&G[i][j][2]);                G[i][j][2]=G[i][j][2]?G[i][j][2]:inf;                G[i+1][j][0]=G[i][j][2];            }        }        rep(i,1,R) rep(j,1,C) rep(u,0,3) rep(v,0,1)        {            d[i][j][u][v]=inf;            done[i][j][u][v]=0;        }        priority_queue<st>Q;        rep(u,0,3)        {            d[r1][c1][u][1]=0;            Q.push((st){r1,c1,u,1,0});        }        while(!Q.empty())        {            st now=Q.top();Q.pop();            if(done[now.r][now.c][now.p][now.t]) continue;            done[now.r][now.c][now.p][now.t]=1;            rep(i,0,3) rep(j,0,1)            {                if(now.t==0&&i!=now.p) continue;                st Next=(st){now.r+dr[i],now.c+dc[i],i,j,d[now.r][now.c][now.p][now.t]+((now.t||j)?2:1)*G[now.r][now.c][i]};                if(ok(Next)&&d[Next.r][Next.c][Next.p][Next.t]>Next.d)                {                    d[Next.r][Next.c][Next.p][Next.t]=Next.d;                    Q.push(Next);                }            }        }        ll ans=inf;        rep(i,0,3) ans=min(ans,d[r2][c2][i][1]);        printf("Case %lld: ",++kase);        if(ans==inf) puts("Impossible");        else printf("%lld\n",ans);    }    return 0;}


0 0