思路
最短路板子题。
显然叫我们求出全源最短路径。
这里有 的 Floyd, 的堆优化 Dijkstra,以及 的 Spfa。
这里直接使用堆优化 Dijkstra 就可以了。
具体来说,求出每个点与所有点的最短路,判一下是否与 相等就好了。
实现
这里使用的是堆优化 Dijkstra,总时间复杂度 ,可以通过此题。
代码:
#include<bits/stdc++.h>
using namespace std;
const int X = 10001, INF = 0x3f3f3f3f;
int nex[X], p, head[X], to[X], val[X], dis[X], vis[X];
int n, x, s;
// 定义结构体 node 用于优先队列
struct node {
int num, dis;
};
// 重载小于运算符,用于优先队列的比较
bool operator <(node a, node b) {
return a.dis > b.dis;
}
priority_queue<node> q;
// 快读函数
inline int read() {
int x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = (x << 1) + (x << 3) + (ch ^ 48);
ch = getchar();
}
return x * f;
}
// 快写函数
inline void write(int x) {
if (x < 0) {
putchar('-');
x = -x;
}
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
// 添加边的函数
void addedge(int u, int v, int w) {
nex[++p] = head[u];
head[u] = p;
to[p] = v;
val[p] = w;
}
// Dijkstra 算法
void dijkstra() {
for (int i = 1; i <= n; i++) dis[i] = INT_MAX;
memset(vis, 0, sizeof(vis));
node t;
t.dis = dis[s] = 0;
t.num = s;
q.push(t);
while (!q.empty()) {
int a = q.top().num;
q.pop();
if (vis[a]) continue;
vis[a] = 1;
for (int i = head[a]; i; i = nex[i]) {
if (!vis[to[i]] && dis[a] + val[i] < dis[to[i]]) {
dis[to[i]] = dis[a] + val[i];
t.num = to[i];
t.dis = dis[to[i]];
q.push(t);
}
}
}
}
int main() {
bool flag = false;
int a, b, c;
// 使用快读读取 n 和 x
n = read();
x = read();
for (int i = 1; i < n; i++) {
// 使用快读读取 a, b, c
a = read();
b = read();
c = read();
addedge(a, b, c);
addedge(b, a, c);
}
for (int k = 1; k <= n; k++) {
s = k;
dijkstra();
for (int j = 1; j <= n; j++) {
if (dis[j] == x) flag = true;
}
}
if (flag) {
const char* yes = "Yes";
for (int i = 0; yes[i]; i++) {
putchar(yes[i]);
}
} else {
const char* no = "No";
for (int i = 0; no[i]; i++) {
putchar(no[i]);
}
}
return 0;
}