#include <bits/stdc++.h>
#define ll long long
#define endl "\n"
using namespace std;
void solve()
{
ll n, m;
cin >> n >> m;
ll b[m], p[m];
vector<ll> eq[n];
for (ll i = 0; i < m; i++)
cin >> b[i] >> p[i], eq[b[i]].push_back(i);
map<ll, ll> dist[m];
dist[0][b[0]] = 0;
deque<pair<ll, ll>> q;
q.push_front(make_pair(0, b[0]));
while (!q.empty())
{
auto [i, j] = q.front();
q.pop_front();
if (j == b[1])
{
cout << dist[1][j] << endl;
return;
}
if (j - p[i] >= 0 and !dist[i].count(j - p[i]))
dist[i][j - p[i]] = dist[i][j] + 1, q.push_back(make_pair(i, j - p[i]));
if (j + p[i] < n and !dist[i].count(j + p[i]))
dist[i][j + p[i]] = dist[i][j] + 1, q.push_back(make_pair(i, j + p[i]));
for (ll k : eq[j])
{
if (!dist[k].count(j))
dist[k][j] = dist[i][j], q.push_front(make_pair(k, j));
if (k == 1)
{
cout << dist[k][j] << endl;
return;
}
}
eq[j].clear();
}
cout << "-1\n";
}
signed main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
ll t = 1;
// precomp();
// cin >> t;
for (ll i = 1; i <= t; i++)
solve();
cerr << "\nTime elapsed: " << clock() * 1000.0 / CLOCKS_PER_SEC << " ms\n";
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
1 ms |
344 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
0 ms |
348 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
0 ms |
348 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
0 ms |
348 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
1 ms |
348 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |