Sicily 1889. Max’s game (優先隊列dijkstra、雜湊)

來源:互聯網
上載者:User

// 題意: 有n*m矩陣,從起點(sx,sy)出發,可以上下左右四個方向移動,// 若兩個位置上是相同字元,則花費為0,否則為1,求到終點的最短距離// 用Dijkstra演算法解決,但會 TLE  ,需要用 優先隊列 最佳化時間#include <iostream>        // 鄰接矩陣+優先隊列實現Dijkstra演算法#include <stdio.h>#include <queue>#include <cstring>using namespace std;                                const int INF=300000;const int MAXN=250000;int n,m,distD[MAXN],done[MAXN];    int sx,sy,tx,ty;    //起點(sx,sy)和終點(tx,ty)int dx[4]={0,0,1,-1},dy[4]={1,-1,0,0};char data[500][500];typedef pair<int,int> pii;void Dijkstra(int st)    //從源點st到其餘各頂點的最短路徑長度{    priority_queue<pii, vector<pii>, greater<pii> > q;    fill(distD,distD+n*m,INF);        //結點下標從0開始,共有 m * n 個結點    distD[st]=0;    fill(done,done+n*m,0);    q.push(make_pair(distD[st], st));    while(!q.empty())     {        pii u = q.top();        q.pop();        int p = u.second;        if(done[p])            continue;        done[p] = 1;        if( p == tx * m + ty )    // 如果探測到終點即可退出        {            printf("%d\n",distD[p]);                break;        }        for(int d=0;d<4;++d)        {            int newx=p/m+dx[d],newy=p%m+dy[d];            int newp=newx*m+newy;            if(newx>=0&&newx<n&&newy>=0&&newy<m&& !done[newp] )            {                int w = ( data[p/m][p%m] == data[newx][newy] ) ? 0 : 1 ;                if( distD[p] + w < distD[newp] )                {                    distD[newp]=distD[p]+w;                    q.push(make_pair(distD[newp], newp));                }            }        }    }}int main(){    while(scanf("%d%d",&n,&m)!=EOF)        // n 行 m 列    {        for(int i=0;i<n;++i)        {            scanf("%s",data[i]);        }        scanf("%d%d%d%d",&sx,&sy,&tx,&ty);        Dijkstra(sx*m+sy);    // 頂點座標[x,y],則在隊列對應的下標是 x * m + y    }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.