2024/12/5日工作总结

完成数据结构pta实验7-2 迪杰斯特拉方法实现最短路径

用迪杰斯特拉算法实现有向网的最短路径

输入格式:
第一行输入有向网的顶点和边数,第二行输入各顶点值,用空格间隔,第三行开始输入各条边的 两个点的及边上的权值,用空格间隔。最后一行输入要求路径的两个顶点。

输出格式:
输出最短路径经过的各顶点,中间用-->连接。

输入样例:
在这里给出一组输入。例如:

6 8
0 1 2 3 4 5
0 2 10
0 4 30
0 5 100
1 2 5
2 3 50
3 5 10
4 3 20
4 5 60
0 3
输出样例:
在这里给出相应的输出。例如:

0-->4-->3

点击查看代码
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

#define MaxInt 32767
#define MVNum 100

typedef int ArcType;
typedef struct{
    int vexs[MVNum];
    ArcType arcs[MVNum][MVNum];
    int vexnum,arcnum;
}AMGraph;

int LocateVex(AMGraph G,int v){
    for(int i = 0;i<G.vexnum;i++){
        if(G.vexs[i] == v)
            return i;
    }
    return -1;
}

void CreateUDG(AMGraph &G){
    cin>>G.vexnum>>G.arcnum;
    for(int i=0;i<G.vexnum;i++){
        cin>>G.vexs[i];
    }
    for(int i=0;i<G.vexnum;i++){
        for(int j=0;j<G.vexnum;j++)
            G.arcs[i][j]=MaxInt;
    }
    for(int k = 0;k<G.arcnum;k++){
        int v1,v2,w;
        cin>>v1>>v2>>w;
        int i = LocateVex(G,v1);
        int j = LocateVex(G,v2);
        if(i != -1&&j != -1){
            G.arcs[i][j]=w;
            G.arcs[j][i]=G.arcs[i][j];
        }
    }
    
}

void ShortestPath_DIJ(AMGraph G,int v0,int v){
    int n = G.vexnum;
    vector<int> S(n,0);
    vector<int> D(n,MaxInt);
    vector<int> Path(n,-1);
    
    for(int v=0;v<n;v++){
        D[v]=G.arcs[v0][v];
        if(D[v]<MaxInt){
            Path[v]=v0;
        }
    }
    S[v0]=true;
    D[v0]=0;

    for(int i=1;i<n;i++){
        int min = MaxInt;
        int v = -1;
        for(int w=0;w<n;w++){
            if(!S[w]&&D[w]<min){
                v = w;
                min = D[w];
            }
        }
        S[v]=true;
        for(int w=0;w<n;w++){
            if(!S[w]&&(D[v]+G.arcs[v][w]<D[w])){
                D[w]=D[v]+G.arcs[v][w];
                Path[w]=v;
            }
        }
    }

    vector<int>shortestPath;
    for(int i=v;i!=-1;i=Path[i]){
        shortestPath.push_back(i);
    }
    reverse(shortestPath.begin(),shortestPath.end());

    for(size_t i=0;i<shortestPath.size();i++){
        if(i>0)
            cout<<"-->";
        cout<<G.vexs[shortestPath[i]];
    }
}


int main(){
    AMGraph G;
    CreateUDG(G);
    int start,end;
    cin>>start>>end;
    ShortestPath_DIJ(G,LocateVex(G,start),LocateVex(G,end));
    return 0;
}
posted @ 2024-12-18 11:17  vivi_vimi  阅读(13)  评论(0)    收藏  举报