城市路(信息学奥赛一本通-T1381)

【题目描述】

罗老师被邀请参加一个舞会,是在城市n,而罗老师当前所处的城市为1,附近还有很多城市2~n-1,有些城市之间没有直接相连的路,有些城市之间有直接相连的路,这些路都是双向的,当然也可能有多条。

现在给出直接相邻城市的路长度,罗老师想知道从城市1到城市n,最短多少距离。

【输入】

输入n, m,表示n个城市和m条路;

接下来m行,每行a b c, 表示城市a与城市b有长度为c的路。

【输出】

输出1到n的最短路。如果1到达不了n,就输出-1。

【输入样例】

​5 5
1 2 20
2 3 30
3 4 20
4 5 20
1 5 100

【输出样例】

90

【源程序】

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define INF 0x3f3f3f3f
#define PI acos(-1.0)
#define N 3001
#define MOD 123
#define E 1e-6
using namespace std;
struct node{
    int pre;
    int next;
    int w;
}a[N*10];
int n,m;
int cnt;
int head[N],vis[N],f[N];
void add(int x,int y,int w)
{
    cnt++;
    a[cnt].pre=y;
    a[cnt].next=head[x];
    a[cnt].w=w;
    head[x]=cnt;

    cnt++;
    a[cnt].pre=x;
    a[cnt].next=head[y];
    a[cnt].w=w;
    head[y]=cnt;
}

int main()
{
    cin>>n>>m;
    for(int i=1;i<=m;i++)
    {
        int x,y,w;
        cin>>x>>y>>w;
        add(x,y,w);
    }
    
    memset(f,INF,sizeof(f));
    f[1]=0;
    vis[1]=1;

    int x=head[1];
    while(x!=0)
    {
        int y=a[x].pre;
        if(f[y]>a[x].w)
            f[y]=a[x].w;
        x=a[x].next;
    }

    int cnt=0;
    while(cntf[k]+w)
                f[y]=f[k]+w;
            x=a[x].next;
        }
    }
    
    if(f[n]==INF)
        cout<<"-1"<

 

你可能感兴趣的:(#,信息学奥赛一本通,#,图论——最短路)