zoukankan      html  css  js  c++  java
  • 自己写的SPFA模板(可打印路径)

    自己写的SPFA模板,可以打印路径。(用静态链表实现的,(静态链表应该不用自己判断重边吧?待验证))
    #include
    #include
    #include
    using namespace std;
    const int MAXE = 10005;
    const int MAXV = 105;
    const int inf = 10000000;
    typedef struct node
    {
    	int s, t, w, next;
    }N;
    
    N edge[MAXE];
    int n;//顶点
    int arrHead[MAXV], arrDis[MAXV], pre[MAXV];
    int inQue[MAXV];
    void init()
    {
    	memset(arrHead, -1 ,sizeof(arrHead));
    	memset(inQue, 0, sizeof(inQue));
    	memset(pre, -1, sizeof(pre));
    }
    
    void SPFA(int s)
    {
    	queue Q;
    	for(int i = 1; i <= n; i++)
    	{
    		arrDis[i] = inf;
    		//pre[i] = i;
    	}
    	Q.push(s);
    	arrDis[s] = 0;
    	inQue[s] = 1;
    
    	while(!Q.empty())
    	{
    		int v = Q.front();
    		Q.pop();
    		inQue[v] = 0;
    
    		for(int ie = arrHead[v]; ie != -1; ie = edge[ie].next)
    		{
    			N e = edge[ie];
    			if(arrDis[e.t] > arrDis[v] + e.w)
    			{
    				arrDis[e.t] = arrDis[v] + e.w;
    				pre[e.t] = v;
    
    				if(!inQue[e.t])
    				{
    					inQue[e.t] = 1;
    					Q.push(e.t);
    				}
    			}
    		}
    	}
    
    }
    
    void printPath(int t)
    {
    	stack S;
    	
    	int p = t;
    	while(1)
    	{
    		p = pre[p];
    		if(p == -1)
    			break;
    		S.push(p);
    	}
    	while(!S.empty())
    	{
    		int a = S.top();
    		S.pop();
    		printf("%d -> ",a);
    	}
    	printf("%d\n", t);
    	
    	return ;
    }
    
    int main(void)
    {
    	int m;
    	while(scanf("%d %d", &n, &m), n || m)
    	{
    		init();
    		int edgeNum = 0, s, t, w;
    		
    		for(int i = 0; i < m; i++)
    		{
    			scanf("%d %d %d", &s, &t, &w);
    			edgeNum++;
    			edge[edgeNum].s = s;
    			edge[edgeNum].t = t;
    			edge[edgeNum].w = w;
    			edge[edgeNum].next = arrHead[s];
    			arrHead[s] = edgeNum;
    
    			edgeNum++;
    			edge[edgeNum].s = t;
    			edge[edgeNum].t = s;
    			edge[edgeNum].w = w;
    			edge[edgeNum].next = arrHead[t];
    			arrHead[t] = edgeNum;
    		}
    
    		SPFA(1);
    		printf("%d\n", arrDis[n]);
    		//printPath(n);
    	}
    	return 0;
    }
    
  • 相关阅读:
    游标cursor
    SQL: EXISTS
    LeetCode Reverse Integer
    LeetCode Same Tree
    LeetCode Maximum Depth of Binary Tree
    LeetCode 3Sum Closest
    LeetCode Linked List Cycle
    LeetCode Best Time to Buy and Sell Stock II
    LeetCode Balanced Binary Tree
    LeetCode Validate Binary Search Tree
  • 原文地址:https://www.cnblogs.com/cchun/p/2520208.html
Copyright © 2011-2022 走看看