#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]);
for (ll i = 0; i < n; i++)
sort(eq[b[i]].begin(), eq[b[i]].end());
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;
return;
}
if (i - j >= 0 and !dist[i - j].count(j) and dist[i - j].size() <= 5000)
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) and dist[i + j].size() <= 5000)
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) and dist[i - k].size() <= 5000)
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) and dist[i + k].size() <= 5000)
dist[i + k][k] = dist[i][j] + 1, q.push(make_pair(i + k, k));
}
eq[i].clear();
if (!dist[b[1]].empty())
{
ll ans = 1e18;
for (auto j : dist[b[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 |
Runtime error |
1 ms |
344 KB |
Execution killed with signal 11 |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Runtime error |
1 ms |
600 KB |
Execution killed with signal 11 |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Runtime error |
1 ms |
348 KB |
Execution killed with signal 11 |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Runtime error |
1 ms |
348 KB |
Execution killed with signal 11 |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Runtime error |
1 ms |
344 KB |
Execution killed with signal 11 |
2 |
Halted |
0 ms |
0 KB |
- |