Dijkstra模板

Dijkstra模板

#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
//重点!!!!!
//写整个程序时一定要map[i][j] = map[j][i] 初始化!!!!! 
const int INF=0x3f3f3f3f;
const int maxn=1005;

int dis[maxn],maps[maxn][maxn],n;
bool vis[maxn];

void Init(){
	for(int i = 1;i <= n;i++){
		dis[i] = INF;
		vis[i] = false;
		for(int j = 1;j <= i; j++)
		    i == j ? maps[i][j] = 0 : maps[i][j] = maps[j][i] = INF;
	}
}

void Dijkstra(int s)
{
	/*for(int i = 1; i <= n; i++) 
	    dis[i] = map[s][i];
	vis[s] = true;
	以上三行为一种Dijkstra 起始方式
	另一种:  (替换以上三句即可)*/
    dis[s] = 0;
    
    for(int i=1;i<=n;i++)
    {
        int p=-1,minn=INF;
        for(int j=1;j<=n;j++)
        {
            if(!vis[j]&&dis[j]

用优先队列优化的Dijkstra 模板

#include
#include
#include
#include
#include
#include
#include
#include
#include
#define INF  0x3f3f3f3f 
#defien maxn 1005
using namespace std;
//重点!!!!!
//写整个程序时一定要maps[i][j] = maps[j][i] 初始化!!!!! 

int dis[maxn],maps[maxn][maxn],n,m;


struct Node{
    int n,v;   //存放结点编号和到初始点的距离 
}node;

bool operator < (Node a,Node b){
    a.v == b.v ? a.n>b.n : a.v>b.v;  //先出小 
}

priority_queue Q;   //优先从小到大

void Init(){
	for(int i = 1;i <= n;i++){
		dis[i] = INF;
		for(int j = 1;j <= i; j++)
		    i == j ? maps[i][j] = 0 : maps[i][j] = maps[j][i] = INF;
	}
}

void Dijkstra(int s){
    while(!Q.empty()) Q.pop();  //清空
	dis[s] = 0;
	Node P;
	P.n = s;
	P.v = 0;
	
	Q.push(P); //将起点放入队列 
	
	while(!Q.empty()){
		
		for(int i = 2; i <= n; i++){
			if(dis[i] > dis[Q.top().n] + maps[Q.top().n][i]){
				dis[i] = dis[Q.top().n] + maps[Q.top().n][i];
				P.n = i;
				P.v = dis[i];
				Q.push(P);
			}
		}
	}
	Q.pop();
}

接下来是邻接表版+优先队列Dijkstra模板

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
#define INF 0xfffffff
#define maxn 1002

struct Node
{
    int e;
    int w;
    friend bool operator < (Node A, Node B)
    {
        return  A.w > B.w;
    }
};

bool vis[maxn];

int m, n;
vector< vector > G;

int Dij(int Star,int End)
{
    Node P, Pn;
    P.e = Star;
    P.w = 0;

    priority_queue Q;

    Q.push(P);

    while( !Q.empty() )
    {
        P = Q.top();
        Q.pop();

        if( vis[P.e] )
            continue;

        vis[P.e] = true;

        if( P.e == End )
            return P.w;

        int len = G[P.e].size();

        for(int i=0; i< len; i++)
        {
            Pn.e = G[P.e][i].e;
            Pn.w = G[P.e][i].w + P.w;

            if( !vis[Pn.e] )
                Q.push(Pn);
        }
    }
    return -1;
}

int main()
{
    Node P;
    while(cin >> n >> m, m+n)
    {
        G.clear();
        G.resize(n+1);

        memset(vis,false,sizeof(vis));

        for(int i=0; i> a >> b >> c;
            P.e = b;
            P.w = c;
            G[a].push_back(P);
            P.e = a;
            G[b].push_back(P);
        }

        int ans = Dij(1,n);

        cout << ans << endl;
    }
    return 0;
}

 

你可能感兴趣的:(最短路径)