题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2544
题目大意:求解最短路
题目思路:裸的dijkstra算法模板题,注意坑点:可能出现重边,所以你要尽量求解出小的边;无向图,两个方向的邻接表都要存储!!
学到的东西:不能用memset初始化非1非0的东西,要用fill(d,d+n,inf),无向图!!!无向图!!!无向图!!!存储邻接表的时候两个方向都要存!!!!
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxv=1e3+10;
const int inf=1e5+10;
struct edge
{
int to;
int cost;
};
typedef pair<int,int> P;//frist 是最短距离,second是顶点编号
int V,E;//定义顶点总数和边的总数
vector<edge>G[maxv];//vector的类型为egde
int d[maxv];
int mmap[maxv][maxv];
void dijkstra(int s)
{
priority_queue<P,vector<P>,greater<P> >que;//这个地方只是固定的格式,这个vector和上边的那个vector没有半毛钱的关系
fill(d,d+V+1,inf);
d[s]=0;
que.push(P(0,s));
while(!que.empty()){ //整个过程类似于bfs,一层一层的很好理解
P p = que.top();que.pop();
int v = p.second;
if(d[v]<p.first) continue;
for(int i=0;i<G[v].size();i++){
edge e=G[v][i];
if(d[e.to]>d[v]+e.cost){
d[e.to] = d[v]+e.cost;
que.push(P(d[e.to],e.to));
}
}
}
}
//建立邻接表的函数
//建立邻接表
bool build()
{
scanf("%d%d",&V,&E);
for(int i=0;i<=V;i++)
for(int j=0;j<=V;j++)
mmap[i][j]=inf;
if(V==0&&E==0) return false;
for(int i=0;i<E;i++){
int s,t,cos;
scanf("%d%d%d",&s,&t,&cos);
if(s<t){if(cos<mmap[s][t]) mmap[s][t]=cos;}
else{if(cos<mmap[t][s])mmap[t][s]=cos;}
}
for(int i=1;i<=V;i++)
for(int j=1;j<=V;j++){
if(mmap[i][j]!=inf){
edge e;
e.to=j,e.cost=mmap[i][j];
G[i].push_back(e);
e.to=i;
G[j].push_back(e);
}
}
dijkstra(1);
printf("%d\n",d[V]);
for(int i=0;i<=V;i++) G[i].clear();
return true;
}
int main()
{
while(build());
}