fork download
  1. #include <cstdio>
  2. #include <stack>
  3.  
  4. using namespace std;
  5.  
  6. int N, M;
  7. int A, B;
  8. int parent[101];
  9.  
  10. stack<int> SA;
  11. stack<int> SB;
  12.  
  13. int main() {
  14. scanf("%d %d %d %d", &N, &A, &B, &M);
  15.  
  16. for (int i = 0; i < M; i ++) {
  17. int x, y;
  18. scanf("%d %d", &x, &y);
  19. parent[y] = x;
  20. }
  21.  
  22. SA.push(A);
  23. while (parent[SA.top()] != 0) {
  24. SA.push(parent[SA.top()]);
  25. }
  26.  
  27. SB.push(B);
  28. while (parent[SB.top()] != 0) {
  29. SB.push(parent[SB.top()]);
  30. }
  31.  
  32. if (SA.top() != SB.top()) {
  33. printf("-1\n");
  34. } else {
  35. while (!SA.empty() && !SB.empty() && SA.top() == SB.top()) {
  36. SA.pop();
  37. SB.pop();
  38. }
  39. printf("%d\n", (int) SA.size() + (int) SB.size());
  40. }
  41.  
  42. return 0;
  43. }
Success #stdin #stdout 0s 3468KB
stdin
9
7 3
7
1 2
1 3
2 7
2 8
2 9
4 5
4 6
stdout
3