HDU 1535 Invitation Cards 最短路 Dijkstra

/*
 * 解題總結 :
 *      1 : 可以用鏈式前向星存圖,避免爆內存。
 *      2 : 需要正向跑一遍最短路,然後方向建邊再跑一遍最短路。
 *      3 : 由於要跑兩遍最短路,所以初始化要特別注意。
 *      4 : 我把讀入數據存了下來,不知道有沒有其他做法,暫時只想到了這個。
 */
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e6 + 10;
const int MAXM = 1e6 + 10;
const int INF = 0x3f3f3f3f;

struct input{
    int u, v, w;
}ds[MAXN];
int n, m;
struct E{
    int to, w, nxt;
}edge[MAXM];
int tot;
int head[MAXM];
priority_queue<pair<int, int>> q;
int disgo[MAXN], disback[MAXN];
bool use[MAXN];

inline void addedge(int u, int v, int w){
    edge[tot].to = v;
    edge[tot].w = w;
    edge[tot].nxt = head[u];
    head[u] = tot++;
}

inline void dijkstra(int* dis){
    while(!q.empty()) q.pop();
    memset(use, false, sizeof use);

    q.push({0, 1});
    while(!q.empty()){
        auto it = q.top();
        q.pop();
        int id = it.second;
        if(use[id]) continue;
        use[id] = true;
        for(int i = head[id]; ~i; i = edge[i].nxt){
            int to = edge[i].to;
            int w = edge[i].w;
            if(dis[id] + w < dis[to]){
                dis[to] = dis[id] + w;
                q.push({-dis[to], to});
            }
        }
    }
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    //cout << setiosflags(ios::fixed) << setprecision(1); //保留小數點後1位
    //cout << setprecision(1); //保留1位有效數字
//    freopen("in.txt", "r", stdin);
//    freopen("out.txt", "w", stdout);

    int t;
    cin >> t;
    while(t--){
        cin >> n >> m;
        tot = 0;
        memset(head, -1, sizeof head);
        for(int i = 1; i <= m; ++i){
            int u, v, w;
            cin >> u >> v >> w;
            ds[i].u = u;
            ds[i].v = v;
            ds[i].w = w;
            addedge(u, v, w);
        }
        memset(disgo, INF, sizeof disgo);
        disgo[1] = 0;
        dijkstra(disgo);
        int ans = 0;
        for(int i = 2; i <= n; ++i) ans += disgo[i];

        tot = 0;
        memset(head, -1, sizeof head);
        for(int i = 1; i <= m; ++i) addedge(ds[i].v, ds[i].u, ds[i].w);
        memset(disback, INF, sizeof disback);
        disback[1] = 0;
        dijkstra(disback);
        for(int i = 2; i <= n; ++i) ans += disback[i];

        cout << ans << endl;
    }
    return 0;
}

 

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