将时间视为一个点,相邻两点连长度0的边,将每个牛连u到v+1的边,spfa即可。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
queue<int> q;
int read()
{
char ch=getchar();int f=0;
while(ch<'0'||ch>'9')ch=getchar();
while(ch>='0'&&ch<='9'){f=(f<<1)+(f<<3)+ch-'0';ch=getchar();}
return f;
}
struct node
{
int from;
int to;
int next;
long long w;
}edge[300005];
int n,m,s,t,head[100005],tot;long long dis[100005];bool vis[100005];
long long inf=9000000000000000000LL;
void add(int u,int v,long long w)
{
edge[tot].from=u;
edge[tot].to=v;
edge[tot].w=w;
edge[tot].next=head[u];
head[u]=tot++;
}
void spfa()
{
q.push(s);
while(!q.empty())
{
int x=q.front();
q.pop();
vis[x]=0;
for(int i=head[x];i!=-1;i=edge[i].next)
{
if(dis[edge[i].to]>dis[x]+edge[i].w)
{
dis[edge[i].to]=dis[x]+edge[i].w;
if(!vis[edge[i].to])
{
vis[edge[i].to]=1;
q.push(edge[i].to);
}
}
}
}
}
int main()
{
memset(head,-1,sizeof(head));
m=read();s=read();t=read()+1;
for(int i=1;i<=m;i++)
{
int u=read(),v=read()+1,w=read();
add(u,v,w);
}
for(int i=1;i<=t;i++)
{
dis[i-1]=inf;
add(i,i-1,0);
}
dis[t]=inf;
dis[s]=0;
spfa();
if(dis[t]==inf)puts("-1");
else printf("%lld",dis[t]);
}