#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(p[i]);
map<ll, ll> dist[n];
dist[b[0]][p[0]] = 0;
queue<pair<ll, ll>> q;
q.push(make_pair(b[0], p[0]));
while (!q.empty())
{
auto [i, j] = q.front();
q.pop();
if (i == b[1])
{
cout << dist[i][j] << endl;
}
if (i - j >= 0 and !dist[i - j].count(j))
dist[i - j][j] = dist[i][j] + 1, q.push(make_pair(i - j, j));
if (i + j < n and !dist[i + j].count(j))
dist[i + j][j] = dist[i][j] + 1, q.push(make_pair(i + j, j));
for (ll k : eq[i])
{
if (i - k >= 0 and !dist[i - k].count(k))
dist[i - k][k] = dist[i][j] + 1, q.push(make_pair(i - k, k));
if (i + k < n and !dist[i + k].count(k))
dist[i + k][k] = dist[i][j] + 1, q.push(make_pair(i + k, k));
}
if (!dist[1].empty())
{
ll ans = 1e18;
for (auto j : dist[1])
ans = min(ans, j.second);
cout << ans << endl;
return;
}
}
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 |
Correct |
0 ms |
344 KB |
Output is correct |
2 |
Runtime error |
1 ms |
348 KB |
Execution killed with signal 11 |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
0 ms |
356 KB |
Output is correct |
2 |
Runtime error |
1 ms |
348 KB |
Execution killed with signal 11 |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
0 ms |
348 KB |
Output is correct |
2 |
Runtime error |
1 ms |
348 KB |
Execution killed with signal 11 |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
0 ms |
348 KB |
Output is correct |
2 |
Runtime error |
1 ms |
348 KB |
Execution killed with signal 11 |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
344 KB |
Output is correct |
2 |
Runtime error |
1 ms |
348 KB |
Execution killed with signal 11 |
3 |
Halted |
0 ms |
0 KB |
- |