Til the Cows Come Home(最短路)

发布于 2020-10-24  0 次阅读


题目大意:

Til the Cows Come Home
有n个点,和m条无向边,每条边具有权值
求从1到n的最短路

思路:

最短路模板题了,注意一下无向边就ez

AC Code:

#include <iostream>
#include <queue>
using namespace std;
#define INF 0x3f3f3f3f
#define ll long long
const int M=2009;
const int N=1009;

int n, m;
ll dis[N];
bool vis[N];
int head[N], cnt;

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 add(int u, int v, ll w) {
    e[++cnt].v = v;
    e[cnt].w = w;
    e[cnt].next = head[u];
    head[u] = cnt;
}

void dijkstra(int s) {
	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() {
	cin >> m >> n;
	for (int i = 1; i <= m; ++i) {
		int u, v;
		ll w;
        cin >> u >> v >> w;
		add(u, v, w);
		add(v, u, w);
	}
	dijkstra(1);
	cout << dis[n] << endl;
	return 0;
}

平平无奇的大学在读本科生