hdu2544最短路(Dijkstra模板题)

题目链接: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());
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值