• 最短路径——Dijkstra(简易版)


    简易之处:顶点无序号,只能默认手动输入0,1,2...(没有灵活性)

    #include <iostream>
    #include <cstdio>
    #include <cstdlib>
    #include <cstring>
    #include <queue>
    #include <malloc.h>
    
    using namespace std;
    
    const int VERTEX_NUM = 20;
    const int INFINITY = 0x3fffffff;
    
    bool vis[VERTEX_NUM];
    int dist[VERTEX_NUM];					// 源点到各点的距离 
    int pre[VERTEX_NUM];
    
    class Graph {
    public:
    	int vexNum;
    	int edgeNum;
    //	int vex[VERTEX_NUM];
    	int arc[VERTEX_NUM][VERTEX_NUM]; 
    };
    
    void createGraph(Graph &G)
    {
    	int i, j, w;
    	cout << "请输入无向图的顶点数和边数:";
    	cin >> G.vexNum >> G.edgeNum;				// 默认顶点序号为0 1 2 3... 
    	for (int i = 0; i != G.vexNum; ++i) {
    		for (int j = 0; j != G.vexNum; ++j) {
    			G.arc[i][j] = INFINITY;
    		}
    	} 
    	for (int k = 0; k != G.edgeNum; ++k) {
    		cout << "请输入边(vi, vj)的顶点i、j以及该边的权w:"; 
    		cin >> i >> j >> w;
    		G.arc[i][j] = w;
    		G.arc[j][i] = w;
    	}
    }
    
    // Dijkstra算法 
    void Dijkstra(Graph &G, int src)
    {
    	memset(vis, false, VERTEX_NUM);
    	memset(dist, INFINITY, VERTEX_NUM); 
    	vis[src] = true;
    	for (int i = 0; i != G.vexNum; ++i) {
    		dist[i] = G.arc[i][src];
    		pre[i] = src;
    	} 
    	int lowcost = INFINITY;
    	int lowcostIndex = src;
    	for (int cnt = 1; cnt != G.vexNum; ++cnt) {
    		lowcost = INFINITY;
    		for (int i = 0; i != G.vexNum; ++i) {
    			if (dist[i] < lowcost && !vis[i]) {
    				lowcost = dist[i];
    				lowcostIndex = i;
    			}
    		}
    		vis[lowcostIndex] = true;
    		for (int i = 0; i != G.vexNum; ++i) {
    			if (!vis[i] && G.arc[lowcostIndex][i] != INFINITY && lowcost + G.arc[lowcostIndex][i] < dist[i]) {
    				dist[i] = G.arc[lowcostIndex][i] + lowcost;
    				pre[i] = lowcostIndex;
    			}
    		}
    	} 
    }
    
    int main()
    {
    	Graph G;
    	createGraph(G);
    	cout << "请输入源点:";
    	int source;
    	cin >> source;
    	Dijkstra(G, source);
    	for (int i = 0; i != G.vexNum; ++i) {
    		if (i == source)	continue;
    		cout << "源点" << source << "到点" << i << "的距离为" << dist[i] << endl; 
    	}
    
    	return 0;
    } 
    

    测试方法及结果:

  • 相关阅读:
    OpenCV和PHP的人脸识别技术
    Nginx下防CC和DDOS攻击
    Centos 6.0 yum 更新源
    linux(centos) 常用命令
    在 Nginx 中配置 Zend Framework
    nginx虚拟主机配置实例
    mysql精简语句集
    nginx rewrite 参数和例子
    nginx 和 subversion
    ZendFramework,php编码规范
  • 原文地址:https://www.cnblogs.com/xzxl/p/8651621.html
Copyright © 2020-2023  润新知