hdu 1874 暢通工程(spfa 鄰接矩陣)
阿新 • • 發佈:2018-04-16
OS ace while ios turn ret stream cto size
題目鏈接
暢通工程,可以用dijkstra算法實現。
聽說spfa很好用,來水一發
鄰接矩陣實現。
鄰接表待整理
#include <stdio.h> #include <algorithm> #include <cmath> #include <cstring> #include <deque> #include <iomanip> #include <iostream> #include <list> #include <map> #include <queue> #include<set> #include <utility> #include <vector> #define mem(arr, num) memset(arr, 0, sizeof(arr)) #define _for(i, a, b) for (int i = a; i <= b; i++) #define __for(i, a, b) for (int i = a; i >= b; i--) #define IO \ ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); using namespace std; typedef long long ll; const ll inf = 0x3f3f3f3f; const double EPS = 1e-10; const ll mod = 1000000007LL; const int N = 200 + 5; int mp[N][N], mp1[N][N]; int dis[N], vis[N]; int V, E; void spfa(int start) { for (int i = 0; i <= V; i++) dis[i] = inf; dis[start] = 0; vis[start] = 1; queue<int> q; q.push(start); while (!q.empty()) { int v = q.front(); q.pop(); vis[v] = 0; for (int i = 1; i <= mp1[v][0]; i++) { if (dis[mp1[v][i]] > dis[v] + mp[v][mp1[v][i]]) { dis[mp1[v][i]] = dis[v] + mp[v][mp1[v][i]]; if (vis[mp1[v][i]] == 0) q.push(mp1[v][i]), vis[mp1[v][i]] = 1; } } } } int main() { int s, e, value; while (cin >> V >> E) { mem(mp,0); mem(mp1,0); mem(vis,0); _for(i, 1, E) { cin >> s >> e >> value; if (mp[s][e] != 0 && mp[s][e] < value) continue; mp1[s][0]++; mp1[s][mp1[s][0]] = e; mp[s][e] = value; //記錄mp度並且記錄每個度的點的下標。 mp1[e][0]++; mp1[e][mp1[e][0]] = s; mp[e][s] = value; } int start, _end; cin >> start >> _end; spfa(start); if (dis[_end] < inf) cout << dis[_end] << endl; else cout << "-1" << endl; } return 0; }
hdu 1874 暢通工程(spfa 鄰接矩陣)