今天我刷题了吗
搜索文档…
A* 算法
1
#include <bits/stdc++.h>
2
3
using namespace std;
4
using ll = long long;
5
using p = pair<int, int>;
6
const int maxn(1e3 + 10);
7
const int maxm(2e5 + 10);
8
int ecnt, head[maxn], rhead[maxn];
9
bool vis[maxn];
10
int g[maxn];
11
12
struct edge {
13
int to, wt, nxt;
14
} edges[maxm];
15
16
template<typename T = int>
17
inline const T read()
18
{
19
T x = 0, f = 1;
20
char ch = getchar();
21
while (ch < '0' or ch > '9') {
22
if (ch == '-') f = -1;
23
ch = getchar();
24
}
25
while (ch >= '0' and ch <= '9') {
26
x = (x << 3) + (x << 1) + ch - '0';
27
ch = getchar();
28
}
29
return x * f;
30
}
31
32
template<typename T>
33
inline void write(T x, bool ln)
34
{
35
if (x < 0) {
36
putchar('-');
37
x = -x;
38
}
39
if (x > 9) write(x / 10, false);
40
putchar(x % 10 + '0');
41
if (ln) putchar(10);
42
}
43
44
inline void addEdge(int u, int v, int w, bool r)
45
{
46
edges[ecnt].to = v;
47
edges[ecnt].wt = w;
48
if (r) {
49
edges[ecnt].nxt = rhead[u];
50
rhead[u] = ecnt++;
51
} else {
52
edges[ecnt].nxt = head[u];
53
head[u] = ecnt++;
54
}
55
}
56
57
void dijkstra(int src)
58
{
59
memset(g, 0x3f, sizeof g);
60
g[src] = 0;
61
priority_queue<p, vector<p>, greater<p>> q;
62
q.push(p(0, src));
63
while (not q.empty()) {
64
int u = q.top().second;
65
q.pop();
66
if (vis[u]) continue;
67
vis[u] = true;
68
for (int i = rhead[u]; compl i; i = edges[i].nxt) {
69
int v = edges[i].to, w = edges[i].wt;
70
if (g[v] > g[u] + w) {
71
g[v] = g[u] + w;
72
q.push(p(g[v], v));
73
}
74
}
75
}
76
}
77
78
int astar(int src, int des, int k)
79
{
80
if (src == des) ++k;
81
auto cmp = [&](const p& a, const p& b) {
82
return a.second + g[a.first] > b.second + g[b.first];
83
};
84
priority_queue<p, vector<p>, decltype(cmp)> q(cmp);
85
q.push(p(src, 0));
86
int cnt = 0;
87
while (not q.empty()) {
88
int u = q.top().first, d = q.top().second;
89
q.pop();
90
if (u == des and ++cnt == k) {
91
return d;
92
}
93
for (int i = head[u]; compl i; i = edges[i].nxt) {
94
int v = edges[i].to, w = edges[i].wt;
95
q.push(p(v, d + w));
96
}
97
}
98
return -1;
99
}
100
101
int main()
102
{
103
#ifndef ONLINE_JUDGE
104
freopen("input.txt", "r", stdin);
105
#endif
106
memset(head, -1, sizeof head);
107
memset(rhead, -1, sizeof rhead);
108
int n = read(), m = read();
109
while (m--) {
110
int u = read(), v = read(), w = read();
111
addEdge(u, v, w, false);
112
addEdge(v, u, w, true);
113
}
114
int s = read(), t = read(), k = read();
115
dijkstra(t);
116
write(astar(s, t, k), true);
117
return 0;
118
}
Copied!
最近更新 11mo ago
复制链接