C++迪杰斯特拉最短路径算法实现

input

第一行表示这个图有4条边,下面五行代表这个图的5条边。

4
0 2 2
0 1 5
1 3 2
2 3 6
-1 0 0
C++迪杰斯特拉最短路径算法实现_第1张图片
输入样例
out

分别输出结点“0”到结点0,1,2,3的最短距离。

0 5 2 7
源码
#include 
#include 
#include 
using namespace std;
#define MAX 10000
#define INF 10000

class edge{
public:

    int to,cost;
    edge(int to,int cost)
    {
        this->to=to;
        this->cost=cost;
    }

};

vector G[MAX];
int d[MAX];
int v;

typedef pair P;

void build()
{
    printf("input v\n");
    scanf("%d",&v);
    while(true)
    {
        int from,to,cost;
        scanf("%d %d %d",&from,&to,&cost);
        if(from<0)
        {
            break;
        }
        G[from].push_back(edge(to,cost));
        G[to].push_back(edge(from,cost));

    }
}

void dijkstra(int s)
{
    priority_queue< P,vector

,greater

> que; fill(d,d+v,INF); d[s]=0; que.push(P(0,s)); while(!que.empty()) { P p=que.top(); que.pop(); int v = p.second; if(d[v]d[v]+e.cost) { d[e.to]=d[v]+e.cost; que.push(P(d[e.to],e.to)); } } } } vector get_path(int des) { vector res; res.push_back(des); //printf("lalalala\n"); while(des!=0) { vector edges = G[des]; //printf("size of edges: %d\n",edges.size()); for(int i=0;i res = get_path(3); printf("从终点3到起点1的最短路径是:\n"); for(int i=0;i

你可能感兴趣的:(C++迪杰斯特拉最短路径算法实现)