POJ 2387 Til the Cows Come Home
题目链接:POJ 2387 Til the Cows Come Home
题目大意:
\(n\)个点\(m\)条边的无向图,求\(1\)到\(n\)的最短路径。
题解:
Dijkstra算法模板题,这里选用优先队列优化。
注意双向边,边数组开两倍。
#include <iostream>
#include <queue>
using namespace std;
#define INF 0x3f3f3f3f
#define N 1000 + 10
#define M 2000 + 10
#define ll long long
#define io_speed_up ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
int head[N], cnt;
int n, m, s;
ll dis[N];
bool vis[N];
struct Node {
int u;
ll dis;
bool operator < (const Node &x) const {
return dis > x.dis;
}
Node(int u, ll dis) : u(u), dis(dis) {}
};
struct Edge {
int v, next;
ll w;
} e[2 * M];
void addEdge(int u, int v, ll w) {
e[++cnt].v = v;
e[cnt].w = w;
e[cnt].next = head[u];
head[u] = cnt;
}
void dijkstra() {
priority_queue <Node> q;
for (int i = 1; i <= n; ++i) {
dis[i] = INF;
vis[i] = false;
}
dis[s] = 0;
q.push(Node(s, 0));
while (!q.empty()) {
Node temp = q.top();
q.pop();
if (vis[temp.u]) {
continue;
}
vis[temp.u] = true;
for (int i = head[temp.u]; i; i = e[i].next) {
int v = e[i].v;
ll len = e[i].w;
if (!vis[v] && dis[v] > dis[temp.u] + len) {
dis[v] = dis[temp.u] + len;
q.push(Node(v, dis[v]));
}
}
}
}
int main() {
io_speed_up;
cin >> m >> n;
s = n;
for (int i = 1; i <= m; ++i) {
int u, v;
ll w;
cin >> u >> v >> w;
addEdge(u, v, w);
addEdge(v, u, w);
}
dijkstra();
cout << dis[1] << endl;
return 0;
}