Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- using namespace std;
- #define INF (1 << 29)
- #define Par pair<int, int>
- #define x first
- #define y second
- int abs(int x)
- {
- if(x < 0)
- return -x;
- return x;
- }
- bool llego(const Par &a, const Par &b)
- {
- int dx = abs(a.x - b.x);
- int dy = abs(a.y - b.y);
- int distMax = 50*50;
- ///Hipotenusa al cuadrado es igual a la suma del cuadrado de los catetos
- ///Con esto evito calcular flotantes
- int hipotenusa = dx*dx + dy*dy;
- return (hipotenusa <= distMax);
- }
- struct Grafo
- {
- vector <vector <int> > adj;
- vector <Par> listaPuntos;
- vector <int> padre;
- void leer()
- {
- int a, b;
- while(cin >> a >> b)
- listaPuntos.push_back(make_pair(a, b));
- adj.resize(listaPuntos.size());
- padre = vector <int> (listaPuntos.size(), -1);
- ///Inicialmente, ningun nodo tiene padre
- for(int i=0; i<listaPuntos.size(); i++)
- {
- for(int j=i+1; j<listaPuntos.size(); j++)
- {
- if(llego(listaPuntos[i], listaPuntos[j]))
- {
- ///Añado esa arista entre los puntos
- adj[i].push_back(j);
- adj[j].push_back(i);
- }
- }
- }
- }
- void BFS(int inicio)
- {
- vector <int> d(listaPuntos.size(), INF);
- queue <int> cola;
- d[inicio] = 0;
- cola.push(inicio);
- while(cola.size())
- {
- int n = cola.front();
- cola.pop();
- for(int i=0; i<adj[n].size(); i++)
- {
- int vecino = adj[n][i];
- if(d[vecino] > d[n] + 1)
- {
- d[vecino] = d[n] + 1;
- padre[vecino] = n;
- cola.push(vecino);
- }
- }
- }
- ///Reconstruyo el camino
- vector <int> nodosSolucion;
- int nodo = listaPuntos.size()-1; ///El ultimo nodo
- if(listaPuntos.size() > 1 && padre[nodo] == -1)
- {
- ///Si en input hay mas de un nodo, y no pude llegar al nodo final
- cout << "NO HAY RUTA." << endl;
- return;
- }
- nodosSolucion.push_back(nodo);
- while(padre[nodo] != -1)
- {
- nodo = padre[nodo];
- nodosSolucion.push_back(nodo);
- }
- ///Ahora lo muestro al reves, o bien uso stack
- for(int i=nodosSolucion.size()-1; i>=0; i--)
- {
- cout << listaPuntos[nodosSolucion[i]].x << " ";
- cout << listaPuntos[nodosSolucion[i]].y << endl;
- }
- }
- };
- int main()
- {
- Grafo g;
- g.leer();
- g.BFS(0);
- return 0;
- }
- /**
- Input:
- 0 0
- -20 -30
- -50 0
- -30 30
- 40 0
- 80 0
- 120 0
- 160 0
- 40 30
- 90 30
- 60 50
- 120 70
- 160 50
- 40 80
- 160 100
- **/
Advertisement
Add Comment
Please, Sign In to add comment