Little mummy to my house (dijsktra algorithm + linked table storage)

Topic description

  AA's Ernie Sauce qwb is an archaeologist. One day qwb discovered a small white and round mummy. It was a crybaby but worked very hard. qwb wanted to give such a cute little mummy to
AA, so she found the courier sister, which made the courier sister worry, because the road to AA's house is too difficult to walk (there may even be no way to get there AA's house), courier sister,
looking for a smart ACMer, I want to ask you to help find the fastest way to AA's house, can you?

Enter description:

In the first line, enter two integers n and m (2<=n<=m<=200000), which respectively indicate that there are n cities and m roads, and the city numbers are 1~n (the city where the express sister is located is 1, and the city where AA is located is located). city ​​is n).
The next m lines, each line input 3 integers u, v, w (u, v <= n, w <= 100000), respectively indicating that there is a road of length w between city u and city v.

Output description:

The output result occupies one line, and output the shortest way to reach AA's house. If there is no way to reach AA's house, output "qwb baka" (do not output double quotation marks).

Idea: disjtra algorithm + linked table storage

xuezhang's code. The classical algorithm is still very rusty.

Code:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const ll LL_INF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1);
const int MAXN = 200009;
int n, m, tot, head[MAXN];
bool vis[MAXN];
ll f[MAXN];
struct Edge
{
	int to, w, nex;
}edge[MAXN * 2];
void init()
{
	to = 0;
	memset(head, -1, sizeof(head));
}
void addedge(int x, int y, int z)
{
	edge[tot] = {y, z, head[x]};
	head[x] = tot++;
}
void solve()
{
	memset(vis, 0, sizeof(vis));
	memset(f, LL_INF, sizeof(f));
	f[1] = 0;
	queue <int> q;
	q.push(1);
	vis[1] = 1;
	while (!q.empty()) {
		int u = q.front(); q.pop();
		vis [u] = 0;
		for (int i = head[u]; i != -1; i = edge[i].nex)
        {
			int v = edge[i].to;
			if (f[u] + edge[i].w < f[v]) {
				f[v] = f[u] + edge[i].w;
				if (!vis[v]) {
					q.push(v);
					force[v] = 1;
				}
			}
		}
	}
}
intmain()
{
	while (~scanf("%d %d", &n, &m)) {
		init();
		for (int i = 1; i <= m; ++i) {
			int x, y, z;
			scanf("%d %d %d", &x, &y, &z);
			addedge(x, y, z);
			addedge(y, x, z);
		}
		solve();
		if (f[n] == LL_INF) puts("qwb baka");
		else printf("%lld\n", f[n]);
	}
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324419974&siteId=291194637