spfa模板

/**
spfa   判断有没有负权值的边;
1.把源点放进队列;

  2.出队 
  用对头进行松弛操作 
  
    3松弛操作的点进队列;
    3如果 改点在队列里就不用进队列;
    
      
 2 .如果进队次数多于n;return ;

  
    
      
        */

#include<iostream>
#include<queue>
using namespace std;
const int maxn=1000+10;
const int INF=0x3ffffff;
int map[maxn][maxn];
int used[maxn];//总进队列次数;
bool qused[maxn];//队列里的元素;
int dis[maxn];//用来更新最短数组;

void init()
{
    int i;
    int j;
    for(i=0;i<maxn;i++)
    {
        used[i]=0;
        qused[i]=0;
        dis[i]=INF;
        for(j=0;j<maxn;j++)
        {
            map[i][j]=INF;
            if(i==j)
            {
                map[i][j]=0;
            
            }
        
        
        
        }
    
    
    
    }






}

int spfa(int num)
{
    queue<int> q;
    //源点进入;
    dis[num]=0;
    q.push(num);
    used[num]++;
    qused[num]=1;
    while(!q.empty())
    {
        int now;
        int k;
        now=q.front();
        q.pop();
        qused[now]=0;
        for(k=1;k<maxn;k++)
        {
            if(used[k]>=maxn)
            {
                return 0;
            
            }
            if(map[now][k]+dis[now]<dis[k])//松弛操作
            {
                dis[k]=map[now][k]+dis[now];
                if(!qused[k])//判断队列里面有没有 k这个点
                {
                    used[k]++;
                    qused[k]=1;
                    q.push(k);
                
                }
            
            }
        
        }
    
    
    
    
    }
    
return 1;
}
int main()
{
    int n,m;
    while(scanf("%d %d",&n,&m)!=EOF,n+m)
    {
        init();
        int x;
        int y;
        int value;
        while(m--)
        {
            cin>>x>>y>>value;
            if(map[x][y]>value)
            {
                map[x][y]=value;
                map[y][x]=value;
            
            }
        
        }//输入完成;
        if(spfa(1))
        {
            printf("%d\n",dis[n]);;
        
        
        }
        else 
        {
            printf("wrong\n");
        }

    
    
    
    }
    

    







return 0;
}

 

posted @ 2013-08-20 11:49  一只蚊子  阅读(165)  评论(0编辑  收藏  举报