比赛时完全没有思路…
网上看了题解,发现用BFS可以做;
AC代码如下:
#include <bits/stdc++.h>
using namespace std;
struct Node{
int d;
int t;
bool operator < (const Node &a) const{
return t>a.t;
}
}; int n,m,k,ans=0;
vector<int>to[10005];
vector<int>a[10005];
priority_queue<Node>pq;
void bfs(){
Node tmp;
tmp.d=1;
tmp.t=0;
pq.push(tmp);
while(!pq.empty()){
if(ans!=0){
break;
}
tmp=pq.top();
pq.pop();
int from=tmp.d;
int tx=tmp.t;
if(tx>1100000){
break;
}
if(from==n&&tx%k==0){
ans=tx;
break;
}
for(int i=0;i<to[from].size();i++){
Node next;
next.d=to[from][i];
if (a[from][i]<=tx){
next.t=tx+1;
}else{
int cha=a[from][i]-tx;
next.t=tx+1+(cha+k-1)/k*k;
}
pq.push(next);
}
}
}
int main(){
cin>>n>>m>>k;
for(int i=1;i<=m;i++){
int u,v,x;
cin>>u>>v>>x;
to[u].push_back(v);
a[u].push_back(x);
}
bfs();
if(ans==0){
cout<<"-1";
}
else cout<<ans;
return 0;
}
通过队列,发现不为空则存入;
再比较时间;
如果结果不为0,输出;
否则输出-1;