POJ 2387

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40924940/article/details/85609794

最短路板子题。。这把用个SPFA。。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int maxn = 5000;
const int INF = 0x3f3f3f3f;
struct node
{
    int to;
    int val;
    int nxt;
}ed[maxn];
int tot,head[maxn];
void add(int a,int b,int v)
{
    ed[++tot].to = b;
    ed[tot].nxt = head[a];
    ed[tot].val = v;
    head[a] = tot;
}
int vis[maxn];
int dis[maxn];
void spfa(int s,int t)
{
    vis[s] = 1;
    dis[s] = 0;
    queue<int> q;
    q.push(s);
    while(q.size())
    {
        int u = q.front();q.pop();
        vis[u] = 0;
        for(int i=head[u];~i;i=ed[i].nxt)
        {
            int to = ed[i].to;
            int v = ed[i].val;
            if(dis[to] > v + dis[u])
            {
                dis[to] = v + dis[u];
                if(!vis[to])
                {
                    vis[to] = 1;
                    q.push(to);
                }
            }
        }
    }
}
int n,m;
int main()
{
    while(~scanf("%d%d",&m,&n))
    {
        memset(head,-1,sizeof head);
        tot = 0;
        for(int i=1;i<=m;i++)
        {
            int a,b,c;
            scanf("%d%d%d",&a,&b,&c);
            add(a,b,c);
            add(b,a,c);
        }
        memset(vis,0,sizeof vis);
        memset(dis,INF,sizeof dis);
        spfa(1,n);
        printf("%d\n",dis[n]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40924940/article/details/85609794