Dijkstra算法之四----优先队列实现Dijkstra算法

//优先队列实现Dijstra 算法
#include <iostream>
#include
<queue>
using namespace std;
#define inf 0x7fffffff //inf表示无穷大
int Vertex,edge[1000][1000],distD[1000],i,j;
typedef pair
<int,int> ele;
void init()
{
for(i=1;i<=Vertex;i++) //结点坐标都是从1开始的
for(j=1;j<=Vertex;j++)
{
if(i==j)
edge[i][j]
=0;
else
edge[i][j]
=inf;
}
}
void Dijstra(int v)
{
int S[1000];
for(i=1;i<=Vertex;i++)
{
distD[i]
=edge[v][i]==0?0:inf;
S[i]
=0;
}
priority_queue
<ele,vector<ele>,greater<ele> > col;

col.push(make_pair(distD[v],v));
//以distD[]来定义优先级
while(!col.empty())
{
ele u
=col.top();col.pop();
int x=u.second;
if(S[x])
continue;
S[x]
=1;
for(j=1;j<=Vertex;j++)
if(!S[j]&&edge[x][j]<inf&&distD[x]+edge[x][j]<distD[j])
{
distD[j]
=distD[x]+edge[x][j];
col.push(make_pair(distD[j],j));
}
}
}
void Dijstra(int v)
{
for(i=1;i<=Vertex;i++)
{
distD[i]
=edge[v][i]==0?0:inf;
}
priority_queue
<ele,vector<ele>,greater<ele> > col;
col.push(make_pair(distD[v],v));
while(!col.empty())
{
ele u
=col.top();col.pop();
int x=u.second;
if(distD[x]!=u.first)
continue;
//上面为了避免重复搜索,设置S[]标识数组,其实只要比较if(distD[x]!=u.first)
//因为col最先删除的是优先级低的元素,所以如果有插入多个distD[x]值,最先出队的是其中的最小值,
//于是后面再检查到x时,u.first肯定不等于distD[x]
for(j=1;j<=Vertex;j++)
if(edge[x][j]<inf&&distD[x]+edge[x][j]<distD[j])
{
distD[j]
=distD[x]+edge[x][j];
col.push(make_pair(distD[j],j));
}
}
}
int main()
{

return 0;
}

  

//sicily 1889. Max’s game   优先队列实现Dijkstra 算法

ContractedBlock.gif ExpandedBlockStart.gif 优先队列实现Dijkstra 算法
#include <iostream>        //优先队列实现Dijkstra 算法
#include<stdio.h>
#include
<queue>
using namespace std;
#define inf 1000000
char table[500][500];
int distD[300000], move[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
typedef pair
<int,int> ele;
int main()
{
int n,m,x1,y1,x2,y2;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=0;i<n;++i)
scanf(
"%s",table[i]);
scanf(
"%d%d%d%d",&x1,&y1,&x2,&y2);
fill(distD,distD
+n*m,inf);
int v=x1*m+y1;
distD[v]
=0;
priority_queue
<ele,vector<ele>,greater<ele> > col;
col.push(make_pair(distD[v],v));

while(!col.empty())
{
ele u
=col.top();col.pop();
int s=u.second,x=s/m,y=s%m;
if(x==x2&&y==y2)
{
printf(
"%d\n",u.first);
break;
}
if(distD[s]!=u.first)
continue;
for(int i=0;i<4;++i)
{
int tx=x+move[i][0],ty=y+move[i][1];
if(tx>=0&&tx<n&&ty>=0&&ty<m)
{
int add=(table[x][y]==table[tx][ty])?0:1;
int t=tx*m+ty;
if(distD[s]+add<distD[t])
{
distD[t]
=distD[s]+add;
col.push(make_pair(distD[t],t));
}
}
}
}
}
return 0;
}

  

转载于:https://www.cnblogs.com/mjc467621163/archive/2011/07/17/2108525.html

你可能感兴趣的:(Dijkstra算法之四----优先队列实现Dijkstra算法)