fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. vector<int> ke[1001];
  4. bool visited[1001];
  5. void DFS(int u){
  6. visited[u] = true;
  7. for(int x : ke[u]){
  8. if(!visited[x]){
  9. visited[x] = true;
  10. DFS(x);
  11. }
  12. }
  13. }
  14. int main(){
  15. int m , n;
  16. cin >> m >> n ;
  17. for(int i = 1 ; i <= n ; i++){
  18. int x,y;
  19. cin >> x >> y;
  20. ke[x].push_back(y);
  21. ke[y].push_back(x);
  22. }
  23. int q;
  24. cin >> q;
  25. while(q--){
  26. int s,t;
  27. cin >> s >> t;
  28. DFS(s);
  29. if(!visited[t]) cout << "-1\n";
  30. else cout << "1\n";
  31. }
  32. }
Success #stdin #stdout 0.01s 5296KB
stdin
5 3
5 4
4 1
4 3
3
4 5
4 2
3 4
stdout
1
-1
1