Skip to content

Instantly share code, notes, and snippets.

@sparfenyuk
Created October 31, 2014 14:46
Show Gist options
  • Select an option

  • Save sparfenyuk/603396238d161d57ed3e to your computer and use it in GitHub Desktop.

Select an option

Save sparfenyuk/603396238d161d57ed3e to your computer and use it in GitHub Desktop.
#include <iostream>
#include <iterator>
#include <deque>
#include <vector>
#include <algorithm>
#include <cassert>
#include <cmath>
using namespace std;
typedef unsigned long long input_type;
typedef vector<vector<input_type> > InputContainer;
#define MAX_VALUE (input_type)-1
void prepare_graph(InputContainer& container, input_type n)
{
container.resize(n);
}
void add_edge(InputContainer& container, input_type from_point, input_type to_point)
{
--from_point; --to_point;
container[from_point].push_back(to_point);
container[to_point].push_back(from_point);
}
int main()
{
input_type n = 0, m = 0;
cin >> n >> m;
InputContainer input;
prepare_graph(input, n);
for (input_type i = 0; i < m; ++i) {
input_type first, second;
cin >> first >> second;
add_edge(input, first, second);
}
input_type from, to;
cin >> from >> to;
--from; --to;
vector<input_type> dist;
dist.resize(n, MAX_VALUE);
deque<input_type> q;
q.push_back(from);
dist[from] = 0;
while (!q.empty()) {
input_type u = q.front();
q.pop_front();
const vector<input_type>& a = input[u];
for (input_type i = 0; i < a.size(); ++i) {
const input_type& v = a[i];
if (dist[v] == MAX_VALUE) {
q.push_back(v);
dist[v] = dist[u] + 1;
}
}
}
if (dist[to] == MAX_VALUE) {
cout << -1;
}
else {
cout << dist[to];
}
return 0;
}
@sparfenyuk
Copy link
Author

Sample Input:
4 4
1 2
4 1
2 3
3 1
2 4
Sample Output:
2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment