dijkstra[two adjacency tables + Priority Queue Optimization]

Source: Internet
Author: User

Dijksta algorithm, if we use the adjacency matrix to save, the 1th waste more space, 2nd we know the algorithm time complexity in O (n*n), such an algorithm can be said is not very good, so we consider optimizing it first we can optimize the storage structure, using adjacency table to store, Secondly we can use priority queue to sort the size, its time complexity is greatly reduced.

It is important to note that the pair is sorted by the size of the first element, and if the same is followed by the second one, we will wrap the d[i] on the first element.

Vector implements adjacency table + priority Queue (assuming that the edge starts out as a character type, so suppose to add difficulty)
#include <iostream> #include <cstdio> #include <vector> #include <map> #include <queue># include<string> #include <cstring> #define INF 0x7fffffffusing namespace Std;const int maxn = 205;int DIS[MAXN  ];int N;  Number of vertices int m; The number of bars of the edge string src,ed;    SRC is the source point, Ed is the target point typedef pair<int,int> PII;STRUCT Edge//build edge structure body {int u;    int V;    int W;    The Edge (int a,int b,int c)//constructor, when constructing the struct, calls this function directly, which makes it convenient to assign a value.        {u = A;        v = b;    W = c; }};map<string,int>m;    The Map association container is used to label the edge of the string type vector<edge> g[maxn];//adjacency table void init () {m.clear ();//Each loop to clear the map int cnt=0;    cin>>n>>m;        string u,v;//character vertex int w;//weight for (int i=1;i<=m;i++) {cin>>u>>v>>w; if (!  M.count (U)) M.insert (Make_pair (u,++cnt)); Make_pair can be used not only in pair<> inserts but also in map,vector and other containers if (!   M.count (v)) M.insert (Make_pair (v,++cnt));        Use the map associative container to label the edge of a string, ... Note that a is not necessarily the edge of number 1th, the first to read into is the edge of the number 1th. Edge E1 (M[U],M[V],W);        Create a non-forward edge, call the constructor, concise.        Edge E2 (M[V],M[U],W); G[m[u]].push_back (E1);    Establishment of adjacency table G[m[v]].push_back (E2);    } cin>>src>>ed; for (int i =1;i<=n;i++) dis[i] = (i = = m[src]? 0:inf);//Initialize Dis}void Dijktra () {priority_queue<pii> que;//priority team The column is the default small element first out of the team Que.push (Make_pair (0,M[SRC)),//The starting point is inserted into the queue, the pair default is the first element priority, so insert priority queue First Popup queue priority is based on dis[] size while (!        Que.empty ()) {PII tmp = Que.top ();        Que.pop ();        int x = Tmp.second;     if (Tmp.first! = Dis[x]) continue; Can avoid duplication of nodes, where each element out of the team is equivalent to the processing of a labeled node, if the team out of this element,//he took the dis, and the current dis is not the same, prove that this node is processed,        This makes it unnecessary to open an array to mark which points have been processed.            for (int i = 0;i < G[x].size (); i++) {int y = G[X][I].V;            int w = G[X][I].W;                if (Dis[x]!=inf&&dis[y] > Dis[x] + W) {Dis[y] = dis[x] + W;            Que.push (Make_pair (dis[y],y)); }}}}int Main () {//FreOpen ("1.in", "R", stdin);    int _;    cin>>_;        while (_--) {init ();        Dijktra ();        if (dis[m[ed]]==inf) cout<< "-1" <<endl;        else cout<<dis[m[ed]]<<endl; /* Output source point sequentially to the distance of ABC, can not directly output the dis sequentially, otherwise the readability is poor, because a point is not necessarily 1th points, point 1th is the first to read the point, so the use of map to point a,b,c according to sort, */for (MAP&LT;STRING,INT&GT;::        Iterator It=m.begin (); It!=m.end (); it++) printf ("%d", Dis[it->second]);    Putchar (' \ n '); } return 0;}
Input data: 1
4 {
D E 13
B C 9
A B 1
A C 12
B D 3
E C 5
D C 4
D F 15
E F 4
A F
Output data: 17
0 1 8 4 13 17 Array Implementation adjacency table + priority queue
#include <iostream> #include <cstdio> #include <cstring> #include <queue> #define INF 0x7fffffffusing namespace Std;const int maxn = 205;int dis[maxn];int u[maxn],v[maxn],w[maxn];int First[MAXN],next[MAXN]    ; int n,m;int src,ed;typedef pair<int,int> pii;void init () {scanf ("%d%d", &n,&m);    Memset (first,-1,sizeof (first));        for (int i=1;i<=m;i++) {scanf ("%d%d%d", &u[i],&v[i],&w[i]);        Next[i]=first[u[i]];        First[u[i]]=i;  U[i+m]=v[i],v[i+m]=u[i],w[i+m]=w[i];        No edge, so add a reverse edge next[i+m]=first[u[i+m]];    First[u[i+m]]=i+m;    } cin>>src>>ed; for (int i=1;i<=n;i++) dis[i]= (i==src 0:inf);//Do not initialize the dis[i] to the direct distance from the source point to each point, otherwise it will be a bit in the team.    }void Dijkstra () {priority_queue<pii>que;    Que.push (Make_pair (0,SRC));        while (!que.empty ()) {PII tmp=que.top ();        Que.pop ();        int x = Tmp.second;  if (tmp.first!=dis[x]) continue;     If this element of the team is out, he brings the dis, and the current dis is not the same, proving that the junction is processed and has identified the shortest path,   for (int e=first[x];e!=-1;e=next[e]) {//This array adjacency table traversal if (Dis[x]!=inf&&dis[v[e]]>dis[x]+w[e]) {                 Dis[v[e]]=dis[x]+w[e];            Que.push (Make_pair (Dis[v[e]],v[e));    }}}}int Main () {//Freopen ("1.in", "R", stdin);    int _;    scanf ("%d", &_);        while (_--) {init ();        Dijkstra ();        if (dis[ed]==inf) cout<< "-1" <<endl;        else cout<<dis[ed]<<endl;    for (int i=1;i<=n;i++) printf ("%d", dis[i]);//Output dist array of Putchar (' \ n ') for each value; }}

Test data: 1
6 9
1 2 1
1 3 12
2 3 9
2 4 3
5 3 5
4 3 4
4 5 13
4 6 15
5 6 4
1 6
Output: 17
0 1 8 4 13 17


dijkstra[two adjacency tables + Priority Queue Optimization]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.