This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
const int LG = 21;
const int N = 400005;
const long long MOD = 1e9 + 7;
const long long INF = 1e9;
const long long INFLL = 1e18;
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<vector<int> > vvi;
typedef vector<ll> vll;
#define forn(i, n) for (int (i) = 0; (i) != (n); (i)++)
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
#define popcount(x) __builtin_popcount(x)
#define popcountll(x) __builtin_popcountll(x)
#define fi first
#define se second
#define re return
#define pb push_back
#define uniq(x) sort(all(x)); (x).resize(unique(all(x)) - (x).begin())
#ifdef LOCAL
#define dbg(x) cerr << __LINE__ << " " << #x << " " << x << endl
#define ln cerr << __LINE__ << endl
#else
#define dbg(x) void(0)
#define ln void(0)
#endif // LOCAL
signed main()
{
int n, m;
cin >> n >> m;
vector<map<int, int> > dist(n);
vector<int> b(m), p(m);
vector<vi> kek(n);
for (int i = 0; i < m; i++) cin >> b[i] >> p[i], kek[b[i]].push_back(p[i]);
deque<pii> q;
int s = b[0], f = b[1];
for (auto i : kek[s])
{
dist[s][i] = 0;
q.push_back({s, i});
}
vector<int> init(n, INF);
init[s] = 0;
while (q.size())
{
pair<int, int> x = q.front();
q.pop_front();
if (init[x.first] == INF)
{
for (auto j : kek[x.fi])
{
if (dist[x.fi].find(j) == dist[x.fi].end())
{
dist[x.fi][j] = dist[x.fi][x.se];
q.push_front({x.fi, j});
}
}
init[x.first] = dist[x.fi][x.se];
}
if (x.fi - x.se >= 0 && dist[x.fi - x.se].find(x.se) == dist[x.fi - x.se].end())
{
dist[x.fi - x.se][x.se] = dist[x.fi][x.se] + 1;
q.push_back({x.fi - x.se, x.se});
}
if (x.fi + x.se < n && dist[x.fi + x.se].find(x.se) == dist[x.fi + x.se].end())
{
dist[x.fi + x.se][x.se] = dist[x.fi][x.se] + 1;
q.push_back({x.fi + x.se, x.se});
}
}
int ans = init[f];
if (ans == INF) cout << -1;
else cout << ans;
}
/* Note:
Check constants at the beginning of the code.
N is set to 4e5 but be careful in problems with large constant factor.
Setting N in every problem is more effective.
Check corner cases.
N = 1
No def int long long for now.
Add something here.
*/
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |