Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdio>
- #include <cstdlib>
- #include <algorithm>
- using namespace std;
- const int INF = (int)1e7 + 10;
- const int N = 500500;
- int n;
- int a[N];
- int ans[N];
- int deg[N];
- int q[N];
- int C;
- int topQ;
- int main()
- {
- freopen("input.txt", "r", stdin);
- freopen("output.txt", "w", stdout);
- scanf("%d", &n);
- for (int i = 0; i < n; i++)
- scanf("%d", &a[i]);
- C = a[n - 1];
- int it = 0;
- for (int x = 0; x <= C; x++)
- {
- ans[x] = INF;
- if (it < n && a[it] < x) it++;
- deg[x] = n - it;
- if (deg[x] == 1)
- {
- ans[x] = 1;
- q[topQ++] = x;
- }
- }
- for (int k = 0; k < topQ; k++)
- {
- int x = q[k];
- it = n - 1;
- while(it >= 0 && x <= a[it])
- {
- int y = a[it] - x;
- if (ans[y] == INF)
- {
- deg[y]--;
- if (deg[y] == 1)
- {
- ans[y] = ans[x] + 1;
- q[topQ++] = y;
- }
- }
- it--;
- }
- }
- int m;
- scanf("%d", &m);
- while(m--)
- {
- int x, y;
- scanf("%d%d", &x, &y);
- int res = min(ans[x], ans[y]);
- if (res == INF)
- printf("-1\n");
- else
- printf("%d\n", res);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement