hdu 1874 最短路 优先队列+dijstra 最短路 1004题 1003题的变形

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <set>
#include <map>
#include <vector>
#include <queue>
#include <ctime>
using namespace std;
const int N = 2000;
const int INF = 1 << 30;
struct Node
{
    int v,next,w;
    bool operator < (const Node &a) const
    {
        return w > a.w;
    }
} Edge[N],t1,t2;
int dis[N],vis[N],head[N],cnt;
int res,ans;
void addEdge(int u,int v,int w)
{
    Edge[cnt].v = v;
    Edge[cnt].next = head[u];
    Edge[cnt].w = w;
    head[u] = cnt++;
}
int dijstra(int  st,int ed)
{
    priority_queue<Node> q;
    for(int i = head[st] ; i != -1 ; i = Edge[i].next)
    {
        int v = Edge[i].v;
        if(Edge[i].w<dis[v])
        {
            dis[v] = Edge[i].w;
            t1.w = dis[v];
            t1.v =  v;
            q.push(t1);
        }
    }
    dis[st]=0;//此句没加错了2次,囧~~~
    vis[st] = 1;
    while(!q.empty())
    {
        t1 = q.top();
        q.pop();
        int u = t1.v;
        if(vis[u]) continue;
        vis[u] = 1;
       // res += dis[u];
      //  ans=max(ans,dis[u]);
        for(int i = head[u]; i != -1; i = Edge[i].next)
        {
            int v = Edge[i].v;
            if(!vis[v] && dis[v]>dis[u]+Edge[i].w)
            {
                dis[v] =dis[u]+Edge[i].w;
                t2.v = v;
                t2.w = dis[v];
                q.push(t2);
            }
        }
    }
    if(dis[ed]==INF)return -1;
    return dis[ed];
}
int main()
{
    int n,m,st,ed;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        memset(head,-1,sizeof(head));
        memset(vis,0,sizeof(vis));
        int u,v,w;
        cnt=0;
        for(int j=1; j<=m; j++)
        {
            cin>>u>>v>>w;
            u++,v++;
            addEdge(u,v,w);
            addEdge(v,u,w);
        }
        scanf("%d%d",&st,&ed);
        for(int i = 0 ; i <=n+1;  i ++) dis[i] = INF;
        res=dijstra(st+1,ed+1);
        printf("%d\n",res);
    }
    return 0;
}
/*
7 9
1 2 28
1 6 10
2 7 14
2 3 16
6 5 25
7 5 24
7 4 18
3 4 12
5 4 22

*/



你可能感兴趣的:(hdu 1874 最短路 优先队列+dijstra 最短路 1004题 1003题的变形)