B3408 [Usaco2009 Oct]Heat Wave 热浪

228 阅读1分钟

image.png

image.png

image.png

按照例子可以这么画:

D4327ABCA20723AF83F41B3B883EAAC1.png

G[n]是个数组,存放着起点是n的边。

优先队列的知识点: blog.csdn.net/wangmj_hdu/…

#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>

using namespace std;

const int MAXV = 2510;
const int INF = 0x3f3f3f3f;

int n, m, s, t;

struct edge{
    int u;
    int v;
    int w;
    edge(int _v, int _w): v(_v), w(_w) {}
    edge(){}
};
struct node{
    int v;
    int d;
    //重载<号,定义优先队列的堆排序方式
    friend bool operator < (const node &a, const node &b){
        return a.d > b.d;
    }
    node(int _v, int _d): v(_v), d(_d) {}
    node() {}
};
//邻接表存每条边
vector<edge> G[MAXV];      
priority_queue<node> pq;
int d[MAXV];
bool vis[MAXV];

void dijkstra(){
    fill(d, d+MAXV, INF);
    fill(vis, vis+MAXV, false);
    pq.push(node(s,0));
    d[s] = 0;
    while(!pq.empty()){
        int u = pq.top().v;
        pq.pop();
        if(vis[u])
            continue;
        vis[u] = true;
        if(u == t){
            printf("%d",d[t]);
            break;
        }
        for(int i = 0; i < G[u].size(); i++){
            int v = G[u][i].v;
            int l = G[u][i].w;
            if(d[u]+l < d[v])
            {
                d[v] = d[u]+l;
                pq.push(node(v, d[v]));
            }
        }
    }
}
int main(){
   	cin>>n>>m>>s>>t;
    for(int i = 1; i <= m; i++){
        int a, b, c;
        cin>>a>>b>>c;
        G[a].push_back(edge(b, c));
        G[b].push_back(edge(a, c));
    }
    dijkstra();
    return 0;
}