#include <iostream>
#include <vector>
#include <bitset>
#include <deque>
#include <algorithm>
#include <cstdlib>
using namespace std;
vector<vector<vector<int> > > a(10001);
vector<int> dist(10001,100001);
int n,m,st,en;
int main(){
cin>>n>>m;
for(int i=0;i<m;i++){
int x,y;
cin>>x>>y;
a[x].push_back({y,1});
a[y].push_back({x,0});
}
cin>>st>>en;
deque<vector<int> > q;
q.push_back({st,0});
dist[st]=0;
while(!q.empty()){
vector<int> u=q.front();
q.pop_front();
for(int i=0;i<a[u[0]].size();i++){
if(dist[a[u[0]][i][0]]>dist[u[0]]+abs(u[1]-a[u[0]][i][1])){
dist[a[u[0]][i][0]]=dist[u[0]]+abs(u[1]-a[u[0]][i][1]);
if(a[u[0]][i][1]==u[1])
q.push_front(a[u[0]][i]);
else
q.push_back(a[u[0]][i]);
}
}
}
int ans1=dist[en];
q.clear();
fill(dist.begin(),dist.begin()+n,100001);
q.push_back({st,1});
dist[st]=0;
while(!q.empty()){
vector<int> u=q.front();
q.pop_front();
for(int i=0;i<a[u[0]].size();i++){
if(dist[a[u[0]][i][0]]>dist[u[0]]+abs(u[1]-a[u[0]][i][1])){
dist[a[u[0]][i][0]]=dist[u[0]]+abs(u[1]-a[u[0]][i][1]);
if(a[u[0]][i][1]==u[1])
q.push_front(a[u[0]][i]);
else
q.push_back(a[u[0]][i]);
}
}
}
cout<<min(ans1,dist[en])<<endl;
}
#include <vector>
#include <bitset>
#include <deque>
#include <algorithm>
#include <cstdlib>
using namespace std;
vector<vector<vector<int> > > a(10001);
vector<int> dist(10001,100001);
int n,m,st,en;
int main(){
cin>>n>>m;
for(int i=0;i<m;i++){
int x,y;
cin>>x>>y;
a[x].push_back({y,1});
a[y].push_back({x,0});
}
cin>>st>>en;
deque<vector<int> > q;
q.push_back({st,0});
dist[st]=0;
while(!q.empty()){
vector<int> u=q.front();
q.pop_front();
for(int i=0;i<a[u[0]].size();i++){
if(dist[a[u[0]][i][0]]>dist[u[0]]+abs(u[1]-a[u[0]][i][1])){
dist[a[u[0]][i][0]]=dist[u[0]]+abs(u[1]-a[u[0]][i][1]);
if(a[u[0]][i][1]==u[1])
q.push_front(a[u[0]][i]);
else
q.push_back(a[u[0]][i]);
}
}
}
int ans1=dist[en];
q.clear();
fill(dist.begin(),dist.begin()+n,100001);
q.push_back({st,1});
dist[st]=0;
while(!q.empty()){
vector<int> u=q.front();
q.pop_front();
for(int i=0;i<a[u[0]].size();i++){
if(dist[a[u[0]][i][0]]>dist[u[0]]+abs(u[1]-a[u[0]][i][1])){
dist[a[u[0]][i][0]]=dist[u[0]]+abs(u[1]-a[u[0]][i][1]);
if(a[u[0]][i][1]==u[1])
q.push_front(a[u[0]][i]);
else
q.push_back(a[u[0]][i]);
}
}
}
cout<<min(ans1,dist[en])<<endl;
}
Comments
Post a Comment