和y总的代码相比少了几行”核心”代码,因为有些东西不用考虑最短路的相关问题,所以删了也没有影响.
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n,m,a,b,c,e[N],ne[N],h[N],idx,dis[N],st[N],w[N],cnt[N];
queue<int> q;
void add(int a,int b,int c)
{
e[idx] = b;w[idx] = c;ne[idx] = h[a];h[a] = idx++;
}
int main()
{
cin >> n >> m;
memset(h,-1,sizeof h);
memset(dis,0x3f,sizeof dis);
for(int i = 1 ; i <= m ; i++) {
cin >> a >> b >> c;
add(a,b,c);
}
for(int i = 1 ; i <= n ; i++){
st[i] = true;
q.push(i);
}
dis[1] = 0;
while(q.size())
{
int t = q.front();
q.pop();
st[t] = false;//出去了
for(int i = h[t] ; i != -1 ; i=ne[i]){
int j= e[i];
if(dis[j]>dis[t]+w[i]){
dis[j] = dis[t]+w[i];
cnt[j] = cnt[t]+1;
//if(st[j]) continue;//保证队列最多只有一个,保证明能够出去
//st[j] = true;//装进去
q.push(j);
if(cnt[j]>=n) {
cout << "Yes" << endl;
return 0;
}
}
}
}
cout <<"No" << endl;
/*if(dis[n]==0x3f3f3f3f) cout << "impossible" << endl;
else cout << dis[n] << endl;*/
return 0;
}