fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. struct edge{
  4. int dau,cuoi,w;
  5. };
  6. bool visited[1001];
  7. int parent[1001];
  8. vector<int> ke[1001];
  9. void DFS(int u){
  10. visited[u] = true;
  11. for(int x : ke[u]){
  12. if(!visited[x]){
  13. parent[x] = u ;
  14. DFS(x);
  15. }
  16. }
  17. }
  18.  
  19. int main(){
  20. int n , m , s , t ;
  21. cin >> n >> m >> s >> t;
  22. for(int i = 1 ; i <= m ; i++){
  23. int x,y;
  24. cin >> x >> y;
  25. ke[x].push_back(y);
  26. ke[y].push_back(x);
  27. }
  28. for(int i = 1 ; i <= n ; i++){
  29. sort(ke[i].begin() , ke[i].end());
  30. }
  31. // nhap
  32. vector<int> res;
  33. DFS(s);
  34. if(!visited[t]){
  35. cout << "-1";
  36. }
  37. else{
  38. while(t != s){
  39. res.push_back(t);
  40. t = parent[t];
  41. }
  42. res.push_back(s);
  43. reverse(res.begin(),res.end());
  44. for(int x : res){
  45. cout << x << " ";
  46. }
  47. }
  48. }
Success #stdin #stdout 0.01s 5276KB
stdin
5 3 4 3
4 2
2 1
3 1
stdout
4 2 1 3