跳到正文

题解

题解:AT_past202109_h 最短経路

Gardenia_Scent约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年1月30日
篇幅
约 3 分钟

版本

  1. v1当前

AT_past202109_h 最短経路

题意:

求出任意 (i,j)(i,j) 之间最短路,当最短路为 xx 时,输出 Yes,没有输出 No。

题目分析

这道题的数据范围比较小,目测可以使用 Dijkstra 算法对每个点进行搜索。

每次收缩距离的时候进行判断,如果和目标距离一致就输出 Yes 并结束程序,否则在程序结尾输出 No。

在程序途中强行结束可以使用 exit(0)exit(0) 实现。

nn 遍 Dijkstra 所需 O(nlogm)O(nlogm) 的时间复杂度,对于 2 秒的题绰绰有余。Floyd(n3)Floyd(n^3)。

直接上 AC 代码:

C++
#include<bits/stdc++.h>
#include<cstring>
#include<queue>
#include<set>
#include<stack>
#include<vector>
#include<map>
using namespace std;
int n,x,u,v,w,d[3005];
vector<int> vv[3005],ww[3005];
bool vis[3005];
/*
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;
}
*/
struct ppp{
	int idx,d;
	bool operator <(const ppp& x)const{return x.d<d;}
};
void Dijkstra(int x){
	memset(d,0x3f,sizeof(d));
	memset(vis,0,sizeof(vis));
	d[x]=0;
	priority_queue<ppp> q;
	q.push({x,0});
	while(q.size()){
		u=q.top().idx;
		q.pop();
		if(vis[u]) continue;
		vis[u]=0;
		for(int i=0;i<vv[u].size();i++){
			v=vv[u][i];
			if(d[v]>d[u]+ww[u][i]){
				d[v]=d[u]+ww[u][i];
				q.push({v,d[v]});
			}
		}
	}
	return;
}
int main(){
	cin>>n>>x;
	for(int i=1;i<n;i++){
		cin>>u>>v>>w;
		vv[u].push_back(v);
		vv[v].push_back(u);
		ww[u].push_back(w);
		ww[v].push_back(w);
	}
	for(int i=2;i<=n;i++){
		Dijkstra(i);
		for(int j=1;j<i;j++){
			if(d[j]==x){
				cout<<"Yes";
				return 0;
			}
		}
	}
	cout<<"No";
	return 0;
}
原文