题目来源:码蹄集
题目描述:
C++代码实现:
参考链接:https://yxsmarter.blog.csdn.net/article/details/128209412?spm=1001.2014.3001.5502
#include <bits/stdc++.h>
using namespace std;
const int maxn = 30000;
const int maxm = 1200000;
const int INF = 1 << 30;
inline int read() {
register int a = 0, po = 1;
char ch = getchar();
while (!isdigit(ch) && ch != '-')
ch = getchar();
if (ch == '-') {
po = -1;
ch = getchar();
}
while (isdigit(ch)) {
a = (a << 1) + (a << 3) + ch - 48;
ch = getchar();
}
return a * po;
}
struct Edge {
int v, w, next;
} e[maxm * 2];
int en, front[maxn];
int n, m, s, t;
inline void addedge(int u, int v, int w) {
en++;
e[en].v = v;
e[en].w = w;
e[en].next = front[u];
front[u] = en;
}
void SPFA() {
int inq[maxn];
int d[maxn];
queue<int> q;
memset(inq, 0, sizeof(inq));
for (int i = 1; i <= n + m; i++)
d[i] = INF;
d[s] = 0;
inq[s] = 1;
q.push(s);
while (!q.empty()) {
int u = q.front();
q.pop();
inq[u] = 0;
for (int i = front[u]; i >= 0; i = e[i].next) {
int v = e[i].v, w = e[i].w;
if (d[v] > d[u] + w) {
d[v] = d[u] + w;
if (!inq[v]) {
inq[v] = 1;
q.push(v);
}
}
}
}
if (d[t] != INF)
cout << d[t];
else
cout << -1;
}
int main() {
memset(front, -1, sizeof(front));
n = read();
n += 2;
for (int i = 1; i <= n - 1; i++) {
for (int j = 1; j <= n - i; j++) {
int tmp = read();
addedge(i, i + j, tmp);
}
}
s = 1, t = n;
SPFA();
return 0;
}
Java代码实现:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
class Main {
static final int maxn = 30000;
static final int maxm = 1200000;
static final int INF = 1 << 30;
static class Edge {
int v, w, next;
public Edge(int v, int w, int next) {
this.v = v;
this.w = w;
this.next = next;
}
}
static int en, n, m, s, t;
static int[] front = new int[maxn];
static Edge[] e = new Edge[maxm * 2];
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
Arrays.fill(front, -1);
n = Integer.parseInt(br.readLine());
n += 2;
for (int i = 1; i <= n - 1; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 1; j <= n - i; j++) {
int tmp = Integer.parseInt(st.nextToken());
addedge(i, i + j, tmp);
}
}
s = 1;
t = n;
SPFA();
}
static void addedge(int u, int v, int w) {
e[en] = new Edge(v, w, front[u]);
front[u] = en;
en++;
}
static void SPFA() {
int[] inq = new int[maxn];
int[] d = new int[maxn];
Queue<Integer> q = new LinkedList<>();
Arrays.fill(inq, 0);
Arrays.fill(d, INF);
d[s] = 0;
inq[s] = 1;
q.add(s);
while (!q.isEmpty()) {
int u = q.poll();
inq[u] = 0;
for (int i = front[u]; i >= 0; i = e[i].next) {
int v = e[i].v;
int w = e[i].w;
if (d[v] > d[u] + w) {
d[v] = d[u] + w;
if (inq[v] == 0) {
inq[v] = 1;
q.add(v);
}
}
}
}
if (d[t] != INF)
System.out.println(d[t]);
else
System.out.println(-1);
}
}
代码提交测试结果:
附B站老师思路讲解,可供参考:https://www.bilibili.com/video/BV1ih4y1x7su/?t=2122.2