Advertisement
Guest User

Untitled

a guest
Jun 13th, 2016
327
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.07 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdio>
  3. #include <cstdlib>
  4. #include <algorithm>
  5. using namespace std;
  6.  
  7. const int INF = (int)1e7 + 10;
  8. const int N = 500500;
  9. int n;
  10. int a[N];
  11. int ans[N];
  12. int deg[N];
  13. int q[N];
  14. int C;
  15. int topQ;
  16.  
  17. int main()
  18. {
  19.     freopen("input.txt", "r", stdin);
  20.     freopen("output.txt", "w", stdout);
  21.  
  22.     scanf("%d", &n);
  23.     for (int i = 0; i < n; i++)
  24.         scanf("%d", &a[i]);
  25.     C = a[n - 1];
  26.     int it = 0;
  27.     for (int x = 0; x <= C; x++)
  28.     {
  29.         ans[x] = INF;
  30.         if (it < n && a[it] < x) it++;
  31.         deg[x] = n - it;
  32.         if (deg[x] == 1)
  33.         {
  34.             ans[x] = 1;
  35.             q[topQ++] = x;
  36.         }
  37.     }
  38.     for (int k = 0; k < topQ; k++)
  39.     {
  40.         int x = q[k];
  41.         it = n - 1;
  42.         while(it >= 0 && x <= a[it])
  43.         {
  44.             int y = a[it] - x;
  45.             if (ans[y] == INF)
  46.             {
  47.                 deg[y]--;
  48.                 if (deg[y] == 1)
  49.                 {
  50.                     ans[y] = ans[x] + 1;
  51.                     q[topQ++] = y;
  52.                 }
  53.             }
  54.             it--;
  55.         }
  56.     }
  57.     int m;
  58.     scanf("%d", &m);
  59.     while(m--)
  60.     {
  61.         int x, y;
  62.         scanf("%d%d", &x, &y);
  63.         int res = min(ans[x], ans[y]);
  64.         if (res == INF)
  65.             printf("-1\n");
  66.         else
  67.             printf("%d\n", res);
  68.     }
  69.  
  70.     return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement