• 堆优化Dijkstra模版


    const int MAXN = 300005;
    const __int64 INF = 0x7FFFFFFF;
    
    typedef struct ENode
    {
    	int v,w;
    	int next;
    }ENode;
    
    struct node
    {
    	int u;
    	__int64 dis;
    	bool operator < (const node &a) const
    	{
    		return dis > a.dis;
    	}
    };
    
    bool vis[MAXN];
    int n, m, first[MAXN];
    __int64 dis[MAXN], ans;
    ENode edge[MAXN];
    priority_queue<node>Q; //node类型的优先队列
    
    void dijkstra()
    {
    	for(int i = 1; i <= n; i++)
    	{
    		vis[i] = false;
    		dist[i] = INF;  //初始最短路程
    	}
    	dis[1] = 0; 
    	node pre, next;
    	pre.u = 1;
    	pre.dis = 0;
    	Q.push(pre);
    	while(!Q.empty())
    	{
    		pre = Q.top();
    		Q.pop();
    		if(vis[pre.u])//除去同时进几次的
    		{
    			continue;
    		}
    		vis[pre.u] = true;
    		dis[pre.u] = pre.dis;
    		for(int i = first[pre.u]; i != -1; i = edge[i].next)
    		{
    			next.u = edge[i].v;
    			if(!vis[next.u] && dist[edge[i].v] > dist[pre.u] + edge[i].w)
    			{
    				next.dis = pre.dis + edge[i].w;
    				Q.push(next);
    			}
    		}
    	}
    }



    const int MAXN = 205;
    const int INF = 999999;
    int n;
    int maps[MAXN][MAXN];
    bool visited[MAXN];
    int pre[MAXN];
    int dist[MAXN];
    
    void init()
    {
    	memset(visited, false, sizeof(visited));
    	for (int i = 1; i <= n; i++)
    	{
    		for (int j = 1; j <= n; j++)
    		{
    			if(i == j)
    			{
    				maps[i][j] = 0;
    			}
    			else
    			{
    				maps[i][j] = INF;
    			}
    		}
    		pre[i] = i;
    		dist[i] = INF;
    	}
    }
    
    void Dijkstra(int s, int e) //起点,终点
    {
    	int i, j;
    	int minValue, minNode;
    
    	dist[s] = 0;
    	visited[s] = true;
    	for (i = 1; i <= n; i++)
    	{
    		dist[i] = maps[s][i];
    		if(dist[i] == INF)
    		{
    			pre[i] = 0;
    		}
    		else
    		{
    			pre[i] = s;
    		}
    	}
    	for (i = 1; i <= n; i++)
    	{
    		minValue = INF;
    		minNode = 0;
    		for (j = 1; j <= n; j++)
    		{
    			if(!visited[j] && minValue > dist[j])
    			{
    				minNode = j;
    				minValue = dist[j];
    			}
    		}
    		if(minNode == 0)
    		{
    			break;
    		}
    		visited[minNode] = true;
    		for (j = 1; j <= n; j++)
    		{
    			if(!visited[j] && maps[minNode][j] != INF && dist[j] > dist[minNode] + maps[minNode][j])
    			{
    				dist[j] = dist[minNode] + maps[minNode][j];
    				pre[j] = minNode;
    			}
    		}
    		if(minNode == e)
    		{
    			break;
    		}
    	}
    }
    


  • 相关阅读:
    UIView动画设置
    窗口与视图的基本概念
    OC基本框架之-字典类型
    将博客搬至CSDN
    objective-c中的深、浅拷贝
    基础算法之二分法查找
    C语言中格式字符指定输出项的数据类型和输出格式总结
    JavaScript学习笔记(9)——JavaScript语法之流程控制
    JavaScript学习笔记(8)——JavaScript语法之运算符
    JavaScript学习笔记(7)——JavaScript语法之函数
  • 原文地址:https://www.cnblogs.com/lgh1992314/p/5835033.html
Copyright © 2020-2023  润新知