zoukankan      html  css  js  c++  java
  • Dijkstra算法模板 C++

    代码出自:《算法竞赛入门经典——训练指南》P328

    #include<iostream>
    #include<vector>
    #include<cstring>
    #include<queue>
    using namespace std;
    const int maxn = 10005;
    const int INF = 2147483647;
    struct Edge{
    	int from,to,dist;
    };
    struct HeapNode{
    	int d,u;
    	bool operator <(const HeapNode & a) const{
    		return d > a.d;
    	}
    };
    struct Dijkstra{
    	int n,m;
    	vector<Edge> edges;
    	vector<int> G[maxn]; 
    	int d[maxn];
    	bool vis[maxn];
    	int p[maxn];
    	
    	void init(int n){
    		this->n = n;
    		for(int i = 0;i <= n;i++)	G[i].clear();
    		memset(vis,false,sizeof vis);
    		for(int i = 0;i <= n;i++)	p[i] = i;
    		for(int i = 1;i <= n;i++)	d[i] = INF;
    	}
    	void add_edge(int from,int to,int dist){
    		edges.push_back(Edge{from,to,dist});
    		m = edges.size();
    		G[from].push_back(m-1);
    	}
    	void dijkstra(int s){
    		priority_queue<HeapNode> q;
    		q.push(HeapNode{0,s});
    		d[s] = 0;
    		while(!q.empty()){
    			HeapNode x = q.top();
    			q.pop();
    			int u = x.u;
    			if(vis[u])	continue;
    			vis[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] = u;
    					q.push(HeapNode{d[e.to],e.to});
    				}
    			}
    		}
    	}
    };
  • 相关阅读:
    HTTPS的七个误解(译文)
    WebLogic 11g重置用户密码
    IT项目管理工具
    Encrypt and Decrypt
    Tomcat Introduction
    浅谈https\ssl\数字证书
    What is POID
    数字签名和数字证书
    Apache Axis2 Practice
    Web Performance Tips
  • 原文地址:https://www.cnblogs.com/long98/p/10352199.html
Copyright © 2011-2022 走看看