601A - The Two Routes - CodeForces Solution


graphs shortest paths *1600

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;

int bfs(vector<int>adj[],int n){
  vector<int>vis(n+1,0);
  queue<int>q;
  q.push(1);
  vis[1]=1;
  int dis=0;
  while(!q.empty()){
    int size=q.size();
    while(size--){
      int node=q.front();
      q.pop();
      if(node==n) return dis;
      for(auto i:adj[node]){
        if(!vis[i]){
          vis[i]=1;
          q.push(i);
        }
      }
    }
    dis++;
  }
  return -1;
}

int main(){
  int n,m;
  cin>>n>>m;
  vector<int>adj1[n+1];
  map<pair<int,int>,int>edge;
  int flag=0;
  for(int i=0;i<m;i++){
    int u,v;
    cin>>u>>v;
    if((u==1 && v==n) || (u==n && v==1)) flag=1;
    edge[{u,v}]++,edge[{v,u}]++;
    adj1[u].push_back(v);
    adj1[v].push_back(u);
  }
  if(!flag) cout<<bfs(adj1,n)<<"\n";
  else{
    vector<int>adj2[n+1];
    for(int i=1;i<=n;i++){
      for(int j=i+1;j<=n;j++){
        if(edge.find({i,j})==edge.end()){
          adj2[i].push_back(j);
          adj2[j].push_back(i);
        }
      }
    }
    cout<<bfs(adj2,n)<<"\n";
  }
}


Comments

Submit
0 Comments
More Questions

1167C - News Distribution
813C - The Tag Game
1130C - Connect
1236B - Alice and the List of Presents
845C - Two TVs
1144D - Equalize Them All
298A - Snow Footprints
1753B - Factorial Divisibility
804A - Find Amir
1541C - Great Graphs
607B - Zuma
30A - Accounting
959C - Mahmoud and Ehab and the wrong algorithm
1215A - Yellow Cards
237B - Young Table
1216D - Swords
271D - Good Substrings
573A - Bear and Poker
10A - Power Consumption Calculation
1244B - Rooms and Staircases
777A - Shell Game
1698D - Fixed Point Guessing
415B - Mashmokh and Tokens
26D - Tickets
471B - MUH and Important Things
982B - Bus of Characters
1102B - Array K-Coloring
818A - Diplomas and Certificates
70A - Cookies
798A - Mike and palindrome