藍橋杯 最短路

                                                                                                                       算法訓練 最短路
問題描述

給定一個n個頂點,m條邊的有向圖(其中某些邊權可能爲負,但保證沒有負環)。請你計算從1號點到其他點的最短路(頂點從1到n編號)。

輸入格式

第一行兩個整數n, m。

接下來的m行,每行有三個整數u, v, l,表示u到v有一條長度爲l的邊。

輸出格式
共n-1行,第i行表示1號點到i+1號點的最短路。
樣例輸入
3 3
1 2 -1
2 3 -1
3 1 2
樣例輸出
-1
-2
數據規模與約定

對於10%的數據,n = 2,m = 2。

對於30%的數據,n <= 5,m <= 10。

對於100%的數據,1 <= n <= 20000,1 <= m <= 200000,-10000 <= l <= 10000,保證從任意頂點都能到達其他所有頂點。


注:裸題,SPFA算法,使用鄰接表和隊列優化

#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
#include <stdio.h>
using namespace std;
#define INF 0xfffffff
queue<int> q;
struct edge
{
    int y;
    int value;
};
int dis[20005],s[20005];
vector<edge> adjmap[200005];
int main()
{
    int n,m,i,j,u,v,l;
    edge tmp;
    cin>>n>>m;
    for(i=0;i<m;i++)
    {
        scanf("%d%d%d",&u,&v,&l);
        tmp.y=v;
        tmp.value=l;
        adjmap[u].push_back(tmp);
    }
    for(i=1;i<=n;i++)
    {
       dis[i]=INF;
    }
    dis[1]=0;
    q.push(1);
    s[1]=1;
    while(!q.empty())
    {
        j=q.front();q.pop();s[j]=0;
        for(i=0;i<adjmap[j].size();i++)
        {
             int t=adjmap[j][i].y;
            if(dis[t]>dis[j]+adjmap[j][i].value)   //首尾不能改變位置,因爲是有向圖
            {
                 dis[t]=dis[j]+adjmap[j][i].value;
                 if(!s[t])
                {
                    s[t]=1;
                    q.push(t);
                }
            }
        }
    }
    for(i=2;i<=n;i++)
        cout<<dis[i]<<endl;
	return  0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章