想请教一下大神,能否使用最短路径相关思路? 尝试了一下,由于最短路径采用的是距离短优先原则,所以会出现靠前的边不能入队的情况。 那么,能否通过一些修改,采用最短路径?
#include<bits/stdc++.h>
using namespace std;
const int M = 500010,N = 50010;
int n,m;
struct E{
int to,nex,v,t;
}e[2*M];
int tot,h[N];
void add_edge(int fr,int to,int v,int t){
e[++tot] = (E){to,h[fr],v,t};
h[fr] = tot;
}
struct node{
int p,nl,nt;
}hd;
int dis[N];
int Dj()
{
memset(dis,0x3f,sizeof(dis));
dis[1] = 0;
queue<node> q;
q.push((node){1,0,0});
while(!q.empty()){
hd = q.front();
q.pop();
for(int i = h[hd.p];i;i = e[i].nex) if(e[i].t == 0||hd.nt < e[i].t){
int to = e[i].to;
int cd = hd.nl + e[i].v;
if(cd < dis[to]){
//printf("%d %d\n",to,cd);
dis[to] = cd;
q.push((node){to,cd,max(e[i].t,hd.nt)});
}
}
}
return dis[n];
}
int main()
{
scanf("%d%d",&n,&m);
for(int i = n;i >= 2;i--) add_edge(i,i-1,0,0);
for(int i = 1;i <= m;i++){
int x,y;
scanf("%d%d",&x,&y);
add_edge(x,y,1,i);
}
printf("%d",Dj());
}