Dijkstra算法

采用BFS搜索,因为bfs比dfs有微弱优势

#include <iostream>
#include<vector>
#include<queue>
#include<cstring>
using namespace std;
 const int maxn=1000+10;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
#define inf 1000000;
struct edge{
    int from,to,dist;
    edge(int u,int v,int w):from(u),to(v),dist(w){}
};
struct heapnode{//用以代替pair,记录u点处的d值
    int d,u;
    bool operator<(const heapnode&rhs) const{
    return d>rhs.d;
    }
};
struct dijkstra{
    int n,m;
    vector<edge> edges;
    vector<int> g[maxn];
    bool done[maxn];//记录是否访问过
    int d[maxn];//记录距离
    int p[maxn];//用来记录导入边
    void init(int n){
        this->n=n;
        for(int i=0;i<n;i++)g[i].clear();
        edges.clear();
    }
    void addedge(int from,int to,int dist){
        edges.push_back(edge(from,to,dist));
        m=edges.size();
        g[from].push_back(m-1);

    }

    void dijlstra(int s){
    priority_queue<heapnode>q;
    for(int i=0;i<n;i++)d[i]=(i==0)?0:inf;  
    memset(done,0,sizeof(done));
    q.push((heapnode){0,s});
    while(!q.empty()){
            heapnode x=q.top();q.pop();//bfs典型语句
            int u=x.u;
            if(done[u])continue;
            done[u]=true;
            for(int i=0;i<g[u].size();i++){
            edge &e=edges[g[u][i]];
            if(d[e.to]>d[u]+e.dist){
                d[e.to]=d[u]+e.dist;
                p[e.to]=g[u][i];
                q.push((heapnode){d[e.to],e.to});
            }   
            }
        }
    }
};

int main(int argc, char** argv) {
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值