Skip to content

Instantly share code, notes, and snippets.

@ArthurLoboLobo
Created March 20, 2023 14:08
Show Gist options
  • Save ArthurLoboLobo/1e7fe7dce4712e7e3976a666912980fc to your computer and use it in GitHub Desktop.
Save ArthurLoboLobo/1e7fe7dce4712e7e3976a666912980fc to your computer and use it in GitHub Desktop.
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 2500+10;
const int infinito = 1e9;
int n, m;
vector<int> viz[MAXN];
int main() {
ios::sync_with_stdio(false); cin.tie(0);
cin >> n >> m;
vector<pair<int,int>> arestas;
for(int i = 1; i <= m; i++) {
int u,v; cin >> u >> v;
arestas.push_back(make_pair(u,v));
viz[u].push_back(v);
viz[v].push_back(u);
}
int resposta = infinito;
for(int i = 0; i < m; i++) {
int a = arestas[i].first;
int b = arestas[i].second;
int dist[n+10];
for(int j = 1; j <= n; j++) {
dist[j] = -1;
}
queue<int> q;
dist[a] = 0;
q.push(a);
// faz uma bfs partindo de a
while(q.size()) {
int u = q.front();
q.pop();
for(auto v : viz[u]) {
if((u == a && v == b) || (u == b && v == a)) continue;
//se for a aresta proibida nao usa
if(dist[v] == -1) {
dist[v] = dist[u]+1;
q.push(v);
}
}
}
if(dist[b] != -1) {
resposta = min(resposta, dist[b]+1);
}
}
if(resposta == infinito) {
cout << -1 << endl;
}
else {
cout << resposta << endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment